0% found this document useful (0 votes)
139 views48 pages

Understanding Spring AOP Advice Types

This document discusses Spring AOP (Aspect Oriented Programming) and how it can be used to separate cross-cutting concerns like logging, authentication, etc. from core business logic in Java applications. It describes problems with mixing these concerns like lack of code reusability. Spring AOP uses aspects to modularize cross-cutting concerns. It defines AOP concepts like join points, pointcuts, advice, and aspects. It provides examples of how to configure different types of advice like before, after, around to add aspects using Spring's AOP features.

Uploaded by

NEERAJ885
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views48 pages

Understanding Spring AOP Advice Types

This document discusses Spring AOP (Aspect Oriented Programming) and how it can be used to separate cross-cutting concerns like logging, authentication, etc. from core business logic in Java applications. It describes problems with mixing these concerns like lack of code reusability. Spring AOP uses aspects to modularize cross-cutting concerns. It defines AOP concepts like join points, pointcuts, advice, and aspects. It provides examples of how to configure different types of advice like before, after, around to add aspects using Spring's AOP features.

Uploaded by

NEERAJ885
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction to Spring AOP
  • Understanding AOP Terminology
  • Types of AOP Advice
  • Implementation Examples
  • Declarative Approach in AOP

Spring AOP:

—----------
In general, in enterprise applications, we will prepare the applications by
using Object orientation style, in Object Orientation style we will provide
the business logic and Services Logic[Authentication, Validations,
Internationalization, Logging,....] in a combined manner.

public class Transaction{


public void deposit(){
—Authentication—-
—Business logic—----
—-Logging—--
—---Transaction—---
}
public void withdraw(){
—Authentication—-
—Business logic—----
—-Logging—--
—---Transaction—---
}
public void transfer(){
—Authentication—-
—Business logic—----
—-Logging—--
—---Transaction—---

}
}

In the above approach, we are able to get the following problems.


1. No Code Reusability, Same services logic we provided repeadly in all
the business methods.
2. No Shareability, Separate individual Services logics are maintained at
each and every Business method.
3. No easy changes in the Services, if we want to provide any updations in
any service then we must change the respective code in all the business
methods.
—-----
—------
To overcome all the above problems we must use AOP, that is Aspect Oriented
Programming.
AOP is a methodology or a set of rules and regulations or a set of
conventions which are applied on the Object oriented Programming in order to
improve Reusability and Shareability.

As per the Aspect Orientation, we have to separate all the services logic
from Business logic, we must declare each and every service as an aspect and
we must provide all the required aspects to the applications at runtime.

In the enterprise applications AOP is able to provide the following


advantages.
1. In AOP, all the business components are very much clean and have only
business logic.
2. All Services are implemented at a common location which simplifies the
Code maintenance.
3. We can make changes in common locations, so that the changes are
available to all business methods.

AOP is implemented by the following vendors.


1. AspectJ
2. Spring AOP
3. JBOSS AOP

Spring Framework is able to provide the AOP like below.


1. Schema Based AOP
2. AspectJ
a. Declarative Approach
b. Annotation Approach
AOP Terminology:
—----------------
1. Aspect
2. Advice
3. Joinpoint
4. Pointcut
5. Target
6. Proxy
7. Weaving
8. Introduction

Aspect:
Aspect is a cross cutting concern or a service which we are going to apply in
the applications.
EX: Logging, Transactions, Security,.....

Advice:
Advice is the actual implementation of the Aspect , that is Aspect is a
concept And the Advice is the implementation of the Aspect.

EX: Logging is an aspect, but the same Logging has so many implementations
like Log4j, JAVA provided Logging,.... Each and every implementation of
Logging which we are going to use in our application is called an Advice.

JoinPoint:
JoinPoint is a point in the application execution where an aspect can be
applied.

Pointcut:
Pointcut is an expression, it represents which Aspects at which join point we
are going to apply in the application.

Target:
It is a Business component to apply all the aspects.

Proxy:
Proxy is an object which has the Target object with all the aspects or
Advices.

Proxy = Target + Advices


Weaving:
Weaving is the process of applying aspects on the target objects in Proxy
objects.

Introduction:
An introduction provides a very good environment to allow adding new methods
or attributes to the existing components without having changes in the code
and giving new behavior to the Component.

Advices in Spring:
—------------------
Advice is the real implementation of the Aspect, Advice is able to provide
the code for implementing Aspects.
EX: Logging is an aspect but it's one of the implementation Log4j is an
advice.

Spring Framework has provided the following advice in AOP.

1. Before Advice
2. After Advice
3. After-Returning Advice
4. After-throwing Advice
5. Around Advice
Before Advice:
—---------------
Before Advice will have the Aspect implementation and it will be executed
just before the Business method execution.

To represent Before Advice , Spring Framework has provided a predefined


interface in the form of “[Link]”.

MethodBeforeAdvice has the following method to execute before executing the


respective business method.

public void before(Method m, Object[] params, Object target)

Where Method is able to provide the complete metadata of a particular


business method.

Where Object[] is able to provide business method parameters.

Where Object is representing a Target object that is the actual Business


Component.

EX:
Public class BeforeAdviceImpl implements MethodBeforeAdvice{
public void before(Method m, Object[] params, Object target){
—---Aspect Implementation—---
}
}

After Advice / After Returning Advice:


—--------------------------------------
It is the same as BeforeAdvice, but it will be executed after executing the
respective Business method.

To represent AfterAdvice, Spring Framework has provided a predefined


interface in the form of “[Link]”.

AfterReturningAdvice has the following method to execute after executing the


Business method.

public void afterReturning(Object returnValue, Object[] args, Object target)

Where Object [First parameter] is representing the return value from the
Business method.
Where Object[] is representing parameters of the Business method.
Where Object [Third parameter] is representing Target object.

public class AfterReturningAdviceImpl implements AfterReturningAdvice{


public void afterReturning(Object returnValue, Object[] args, Object
target){
—--implementation—--
}
}

Note: In Schema based implementation, AfterAdvice and AfterReturningAdvice


are same , but in Annotation based Approach AfterAdvice and
AfterReturningAdvice are different.

ThrowsAdvice / After-Throwing Advice:


—-------------------------------------
This advice will have the aspect implementation , it will be executed when we
get an exception in the Business method.

To represent this advice Spring Framework has provided a predefined interface


in the form of “[Link]”.

The above interface has the following method to execute after getting an
Exception.

public void afterThrowing(Method m, Object[] params, Object target, Throwable


t)

Where Method is able to provide metadata of the Business method.


Where Object[] represents Business method parameters.
Where Object is representing a Target object.
Where Throwable represents the exception which we have in the Business
Method.

public class ThrowsAdviceImpl implements ThrowsAdvice{


public void afterThrowing(Method m, Object[] params, Object target,
Throwable t){
—----
}

}
AroundAdvice:
—------------
This advice will be executed before and after the business method execution.

It is the combination of BeforeAdvice and AfterAdvice.

To represent AroundAdvice we have a predefined interface in the form of


“[Link]”.

The MethodInterceptor interface was provided by a third party organization


named “AOPAlliance” and it is supported by All the AOP implementations like
SPring AOP.

MethodInterceptor has the following method to execute before and after


business methods.

public Object invoke(MethodInvocation mi)throws Throwable

Where MethodInvocation has a proceed() method inorder to execute the Business


method.

public class AroundAdviceImpl implements MethodInterceptor{


public object invoke(MethodInvocation mi)throws Throwable{
—----Before Advice Logic—----
Object returnValue = [Link]();
—----After Advice Logic—-----
return returnValue;
}
}

Pointcut:
Pointcut defines at what joinpoint what advice/Advices has/have to be
applied.

If we want to provide Pointcuts in Spring Framework then we must configure


Pointcut and its expressions in the Spring Configuration file.

In Spring Framework there are two types of Pointcuts.

1. Static Pointcut
2. Dynamic Pointcut
Static pointcut:
Static Pointcut defines the advice that is always [Link] Spring
applications we will define static pointcuts on the basis of the business
method and target class.

To represent PointCuts in Spring applications Spring Framework has provided a


predefined interface in the form of “[Link]”.

Spring framework has provided the following implementation classes for the
PointCut interface.

1. NameMatchMethodPointCut
2. Perl5RegexprMethodPointCut
3. JdkRegexMethodPointCut
—----
—----
Dynamic Pointcut:
DynamicPointcut is a pointcut, it will determine if the advice should be
executed or not on the basis of the runtime method arguments.

EX:
1. ControlFlowPointCut
2. DynamicMethodMatcherpointCut

If we want to use Pointcuts in Spring applications then we have to configure


Pointcut and Advisor in the Spring Configuration file.

In Spring Applications, in general we will use “DefaultPointCutAdvisor”


inorder to suggest the advice for the join points.

If we want to use NameMatchMethodPointCut in Spring applications then we have


to use the “mappedNames” property of type array and we must provide business
method names as values to which advice we want to apply.

<bean id=”pointcut”
class=”[Link]”>
<property name=”mappedNames”>
<array>
<value>deposit</value>
<value>withdraw</value>
<value>transferFunds</value>
</array>
</property>
</bean>

Perl5RegexprMethodPointCut and JdkRegexMethodPointCut are able to provide


advice by matching the provided regular expression to the Business methods;
these pointcuts require the “pattern” property where we must define regular
expression.

<bean id=”pointcut”
class=”[Link].Perl5RegexmethodPointcut”>
<property name=”pattern”>
<list>
<value>EmployeeService.*</value>
</list>
</property>
</bean>

<bean id=”advisor”
class=”[Link]”>
<property name=”pointcut” ref=”pointcut”/>
<property name=”advice” ref=”advice”/>
</bean>

To prepare AOP applications we have to use the following steps.


1. Create Bean components as per the requirements.
2. Create Service Interface and Service class.
3. Create Advice class
4. Prepare Configuration file with the following configurations.
a. Bean configuration
b. Service Class Configuration
c. Advice configuration
d. Pointcut configuration
e. Advisor Configuration
f. Proxy Configuration
5. Create a Test Application and access the business method.
EXample on Before Advice:
[Link]
package [Link];

public class Employee {


private int eno;
private String ename;
private float esal;
private String eemail;
private String emobile;

public int getEno() {


return eno;
}

public void setEno(int eno) {


[Link] = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


[Link] = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


[Link] = esal;
}

public String getEemail() {


return eemail;
}

public void setEemail(String eemail) {


[Link] = eemail;
}
public String getEmobile() {
return emobile;
}

public void setEmobile(String emobile) {


[Link] = emobile;
}
}

[Link]
package [Link];

import [Link];

public interface EmployeeService {


public void displayEmployee(Employee employee);
}

[Link]
package [Link];

import [Link];

public class EmployeeServiceImpl implements EmployeeService{


@Override
public void displayEmployee(Employee employee) {
[Link]("Employee Details");
[Link]("-------------------------");
[Link]("Employee Number :
"+[Link]());
[Link]("Employee Name :
"+[Link]());
[Link]("Employee Salary :
"+[Link]());
[Link]("Employee Email Id :
"+[Link]());
[Link]("Employee Mobile :
"+[Link]());
}
}

[Link]
package [Link];
import [Link];
import [Link];

import [Link];

public class EmployeeValidatorAdvice implements MethodBeforeAdvice {


@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
Employee employee = (Employee) args[0];
[Link]("Validation Messages for
"+[Link]());

[Link]("================================================"
);
int eno = [Link]();
if(eno == 0){
[Link]("Employee Number Is Required");
}else{
if(eno < 100 || eno > 999){
[Link]("Employee Number Must be 3 digit
number");
}
}
String ename = [Link]();
if(ename == null || [Link]("")){
[Link]("Employee Name Is Required");
}

float esal = [Link]();


if(esal == 0.0f){
[Link]("Employee Salary is Required");
}else{
if(esal < 10000.0f){
[Link]("Employee Salary Must be minimum
10000");
}
}

String eemail = [Link]();


if(eemail == null || [Link]("")){
[Link]("Employee Email Id Is Required");
}else{
if(![Link]("@[Link]"))
[Link]("Invalid Email Id, Hint:
xxxx@[Link]");
}

String emobile = [Link]();


if(emobile == null || [Link]("")){
[Link]("Employee Mobile Number Is required");
}else{
String[] mobileNo = [Link]("-");// 91-9988776655
if(!mobileNo[0].equals("91")){
[Link]("Invalid Mobile Number, Mobile
Number Must be started with 91-");
}
if(mobileNo[1].length() != 10){
[Link]("Invalid Mobile number, Mobile
number must be a 10 digit number");
}
}
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import
[Link];

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("[Link]");
//EmployeeService employeeService1 = (EmployeeService)
[Link]("employeeService");
EmployeeService employeeServiceProxy = (EmployeeService)
[Link]("proxy");
Employee employee = (Employee)
[Link]("employee");
[Link](employee);
}
}

[Link]
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]

[Link]
<bean id="employee" class="[Link]">
<property name="eno" value="123"/>
<property name="ename" value="Durga"/>
<property name="esal" value="50000"/>
<property name="eemail" value="durga@[Link]"/>
<property name="emobile" value="91-9988776655"/>
</bean>

<!-- Target -->


<bean id="employeeService"
class="[Link]"/>

<!-- Advice: Aspect implementation -->


<bean id="validatorAdvice"
class="[Link]"/>

<!-- Pointcut: List of Business methods to apply Advices.-->


<bean id="pointcut"
class="[Link]">
<property name="mappedNames">
<array>
<value>displayEmployee</value>
</array>
</property>
</bean>

<!-- Advisor: Mapping between Advice and Pointcut -->


<bean id="advisor"
class="[Link]">
<property name="advice" ref="validatorAdvice"/>
<property name="pointcut" ref="pointcut"/>
</bean>

<!-- Proxy: Target + Advisors -->


<bean id="proxy"
class="[Link]">
<property name="target" ref="employeeService"/>
<property name="interceptorNames">
<list>
<value>advisor</value>
</list>
</property>
</bean>

</beans>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>springaopapp01</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>

<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
</dependencies>
</project>

Example on After Advice


—---------------------
[Link]
package [Link];

public class Student {


private String sname;
private String squal;
private String semail;
private String smobile;
private String saddr;

public String getSname() {


return sname;
}

public void setSname(String sname) {


[Link] = sname;
}

public String getSqual() {


return squal;
}

public void setSqual(String squal) {


[Link] = squal;
}

public String getSemail() {


return semail;
}

public void setSemail(String semail) {


[Link] = semail;
}

public String getSmobile() {


return smobile;
}
public void setSmobile(String smobile) {
[Link] = smobile;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


[Link] = saddr;
}
}

[Link]
package [Link];

import [Link];

public interface InstituteService {


public void courseEnquiry(Student student, String courseName);
public void courseRegistration(Student student, String
courseName);
}

[Link]
package [Link];

import [Link];

public class InstituteServiceImpl implements InstituteService{

@Override
public void courseEnquiry(Student student, String courseName) {
[Link]("Student Course Enquiry Details");
[Link]("---------------------------------");
[Link]("Student Name :
"+[Link]());
[Link]("Student Qualification :
"+[Link]());
[Link]("Student Email Id :
"+[Link]());
[Link]("Student Mobile Number :
"+[Link]());
[Link]("Student Address :
"+[Link]());
[Link]("Student Course Name : "+courseName);
}

@Override
public void courseRegistration(Student student, String courseName)
{
[Link]("Student Course Registration Details");
[Link]("---------------------------------");
[Link]("Student Name :
"+[Link]());
[Link]("Student Qualification :
"+[Link]());
[Link]("Student Email Id :
"+[Link]());
[Link]("Student Mobile Number :
"+[Link]());
[Link]("Student Address :
"+[Link]());
[Link]("Student Course Name : "+courseName);
}
}

[Link]
package [Link];

import [Link];
import [Link];

import [Link];

public class ThanqAdvice implements AfterReturningAdvice {


@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
Student student = (Student) args[0];
String courseName = (String) args[1];

[Link]("ThanQ "+[Link]()+" for your


"+[Link]()+" on the Course "+courseName);
[Link]("Durgasoft Team will be in touch with you
for further Scheduling.");
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import
[Link];

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("[Link]");
InstituteService instituteService = (InstituteService)
[Link]("proxy");
Student student = (Student)
[Link]("student");
[Link](student, "JAVA");

[Link]();

[Link](student, "JAVA");

}
}

[Link]
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]

[Link]
<bean id="student" class="[Link]">
<property name="sname" value="Durga"/>
<property name="squal" value="MTech"/>
<property name="semail" value="durga@[Link]"/>
<property name="smobile" value="91-9988776655"/>
<property name="saddr" value="Hyd"/>
</bean>

<!-- Target -->


<bean id="target"
class="[Link]"/>

<!-- Advice -->


<bean id="advice" class="[Link]"/>

<!-- Proxy -->


<bean id="proxy"
class="[Link]">
<property name="target" ref="target"/>
<property name="interceptorNames">
<list>
<value>advice</value>
</list>
</property>
</bean>
</beans>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>springaopapp02</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>

<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
</dependencies>

</project>

Example on Throws Advice:


[Link]
package [Link];

public class Movie {


private String movieName;
private String showTime;
private int price;

public String getMovieName() {


return movieName;
}

public void setMovieName(String movieName) {


[Link] = movieName;
}

public String getShowTime() {


return showTime;
}

public void setShowTime(String showTime) {


[Link] = showTime;
}

public int getPrice() {


return price;
}

public void setPrice(int price) {


[Link] = price;
}
}

[Link]
package [Link];

import [Link];

public interface MovieService {


public void playMovie(Movie movie)throws Exception;
}

[Link]
package [Link];

import [Link];

public class MovieServiceImpl implements MovieService {

@Override
public void playMovie(Movie movie) throws Exception {
[Link]("Movie "+[Link]()+" Started at
"+[Link]());
throw new RuntimeException("Power Failure Occurred");
}
}

[Link]
package [Link];

import [Link];

import [Link];

public class MoneyReturnAdvice implements ThrowsAdvice {


public void afterThrowing(Method method, Object[] params, Object
target, Exception exception){
[Link]([Link]()+" , Movie was
Stopped, Please contact to the Theater Manager to get back your
Money");
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import
[Link];

public class Main {


public static void main(String[] args){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("[Link]");
MovieService movieService = (MovieService)
[Link]("proxy");
Movie movie = (Movie) [Link]("movie");
try {
[Link](movie);
} catch (Exception e) {

}
}
}

[Link]
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]

[Link]
<!-- Movie -->
<bean id="movie" class="[Link]">
<property name="movieName" value="Bahubali"/>
<property name="showTime" value="9:00PM"/>
<property name="price" value="500"/>
</bean>

<!-- Target -->


<bean id="target" class="[Link]"/>

<!-- Advice -->


<bean id="advice"
class="[Link]"/>

<!-- Proxy -->


<bean id="proxy"
class="[Link]">
<property name="target" ref="target"/>
<property name="interceptorNames">
<list>
<value>advice</value>
</list>
</property>
</bean>
</beans>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>springaopapp03</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>

<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
</dependencies>

</project>
Example on AroundAdvice:
[Link]
package [Link];

public class Account {


private String accNo;
private String accHolderName;
private String accType;
private int balance;

public String getAccNo() {


return accNo;
}

public void setAccNo(String accNo) {


[Link] = accNo;
}

public String getAccHolderName() {


return accHolderName;
}

public void setAccHolderName(String accHolderName) {


[Link] = accHolderName;
}

public String getAccType() {


return accType;
}

public void setAccType(String accType) {


[Link] = accType;
}

public int getBalance() {


return balance;
}

public void setBalance(int balance) {


[Link] = balance;
}
}

[Link]
package [Link];

public class Cheque {


private String chequeNumber;
private int amount;

public String getChequeNumber() {


return chequeNumber;
}

public void setChequeNumber(String chequeNumber) {


[Link] = chequeNumber;
}

public int getAmount() {


return amount;
}

public void setAmount(int amount) {


[Link] = amount;
}
}

[Link]
package [Link];

import [Link];
import [Link];

public interface TransactionService {


public void debit(Account account, Cheque cheque);
}

[Link]
package [Link];

import [Link];
import [Link];
public class TransactionServiceImpl implements TransactionService{

@Override
public void debit(Account account, Cheque cheque) {
[Link]("**********Transaction START*********");
int initialAmount = [Link]();
int debitAmount = [Link]();
int totalAmount = initialAmount - debitAmount;
[Link](totalAmount);
[Link]("********Transaction Success*********");
[Link]("********Amount is debited from
Account*******");
[Link]("********Transaction END*********");
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class ChequeClearenceAdvice implements MethodInterceptor {


@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
Object[] params = [Link]();
Account account = (Account) params[0];
Cheque cheque = (Cheque) params[1];

[Link]("Dear Customer!, a Cheque with the number


"+[Link]()+" is coming for clarence, please maintain
the proper amount in your account ");
[Link]();
[Link]("Dear Customer!, the Account Number
"+[Link]()+" has been debited the amount
"+[Link]()+" in the clerence of the cheque with the cheque
number "+[Link]()+" Now the total Amount is
"+[Link]());
return null;
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("[Link]");
Account account = (Account)
[Link]("account");
Cheque cheque = (Cheque) [Link]("cheque");

TransactionService transactionService = (TransactionService)


[Link]("proxy");
[Link](account, cheque);

}
}

[Link]
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]

[Link]
<!-- Beans -->
<bean id="account" class="[Link]">
<property name="accNo" value="abc123"/>
<property name="accHolderName" value="Durga"/>
<property name="accType" value="Savings"/>
<property name="balance" value="50000"/>
</bean>
<bean id="cheque" class="[Link]">
<property name="chequeNumber" value="1234556789"/>
<property name="amount" value="10000"/>
</bean>

<!-- target -->


<bean id="target"
class="[Link]"/>

<!-- Advice -->


<bean id="advice"
class="[Link]"/>

<!-- Proxy -->


<bean id="proxy"
class="[Link]">
<property name="target" ref="target"/>
<property name="interceptorNames">
<list>
<value>advice</value>
</list>
</property>
</bean>

</beans>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>springaopapp04</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>
<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
</dependencies>

</project>

AspectJ:
—--------
AspectJ is a language, it is able to represent AOP and it has provided
specialized syntaxes to express concerns.

AspectJ is supported by Spring in the following two approaches.

1. Declarative Approach.
2. @Aspectj annotation style approach.

1. Declarative Approach:
—------------------------
IN declarative approach, we will use a set AOP tags which are provided by
the AOP namespace in the Spring COnfiguration file in order to declare
Aspects, Advices, Pointcuts,.....

[Link]
—----------------
<beans ………..
xmlns:aop="[Link]
xsi:schemaLocation="
[Link]
[Link]
—-----
<aop:config>
—-----
</aop:config>
—---
</beans>

Where <aop:config> tag will have all the aspects configuration and all the
specific business methods related configurations like
advice,pointcuts,....

1. Declaring Aspects:
To declare Aspects by using AOP tags we have to use the following tags in
the Spring Configuration file.

<beans …… >
—--
<aop:config>
<aop:aspect id=”--” ref=”---”/>
—---
</aop:config>
—--
</beans>

EX:
<beans>
<bean id=”loggingBean”
class=”[Link]”/>
<aop:config>
<aop:aspect id=”loggingAspect” ref=”loggingBean”>
—---
</aop:aspect>
</aop:config>

</beans>

[Link] Pointcuts:
A pointcut helps in determining the join points to be executed with
different advices.
<beans…..>
<aop:config>
<aop:aspect id=”--” class=”---”>
<aop:pointcut id=”--” expression=”---”/>
—----
</aop:aspect>
</aop:config>
</beans>

EX:
<beans>
<bean id=”loggingBean”
class=”[Link]”/>
<aop:config>
<aop:aspect id=”loggingAspect” ref=”loggingBean”>
<aop:pointcut id=”logPointcut”
expression=”execution(*
[Link].*(...))”
/>
</aop:aspect>
</aop:config>

</beans>

Example on pointcut Expressions:


1. execution(* [Link].*(..))
This expression is able to represent all the business methods which are
available in EmployeeService and having any number of parameters and
having any access modifier and any Return type

2. execution(* EmployeeService.*(..))
This expression is able to represent all the business methods which are
available in EmployeeService in the current package and having any number
of parameters and having any access modifier and any Return type.

3. execution(public * [Link].*(..)):
This expression is able to represent all the business methods which are
available in EmployeeService , which are declared with public and which
are having any return type and which are having any number of parameters.
4. execution(public Employee [Link].*(..)):
This expression is able to represent all the business methods which are
having public access modifiers , which are having only Employee return
type and which are having any number of parameters.

5. execution(public Employee
[Link].*(Employee ,..)):
This expression is able to represent all the business methods of
EmployeeService which are having public access modifiers, which are having
Employee return type and which are having the first parameter is Employee.

6. execution(public Employee EmployeeService.*(Employee, Integer)):


This expression is able to represent all the business methods of the
EmployeeService which are having public access modifier, which are having
the Employee return type, Which are having Employee and Integer
parameters.

3. Declaring Advices:
—--------------------
Spring AspectJ is providing the following five advices.
1. <aop:before>
2. <aop:after>
3. <aop:after-returning>
4. <aop:around>
5. <aop:after-throwing>
In all the above advices, there are two attributes.
1. Method: it will take an advice method name.
2. pointcut-ref: it will take pointcut reference value.

EX:
<beans>
<bean id=”loggingBean”
class=”[Link]”/>
<aop:config>
<aop:aspect id=”loggingAspect” ref=”loggingBean”>
<aop:pointcut id=”logPointcut”
expression=”execution(*
[Link].*(...))”
/>
<aop:before method=”logBefore”
pointcut-ref=”logPointcut”/>
<aop:after method=”logAfter”
pointcut-ref=”logPointcut”/>
—--
</aop:aspect>
</aop:config>

</beans>

To prepare Applications by using ASPECTJ then we have to use the following


steps.
1. Declare beans
2. Declare Service interface
3. Declare Service implementation class
4. Declare Aspect class
5. Prepare Spring Configuration File
6. Prepare test Application

EX:
—--
[Link]
package [Link];

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


[Link] = eno;
}

public String getEname() {


return ename;
}
public void setEname(String ename) {
[Link] = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


[Link] = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


[Link] = eaddr;
}
}

[Link]
package [Link];

import [Link];

public interface EmployeeService {


public String createEmployee(Employee employee)throws Exception;
public Employee searchEmployee(int eno);
public String updateEmployee(Employee employee);
public String deleteEmployee(Employee employee);

[Link]
package [Link];

import [Link];

public class EmployeeServiceImpl implements EmployeeService{

@Override
public String createEmployee(Employee employee) throws Exception {
[Link]("Employee "+[Link]()+" Inserted
Successfullt from createEmployee() method");
return "SUCCESS";
}

@Override
public Employee searchEmployee(int eno) {
[Link]("Employee "+eno+" found from
searchEmployee() method");
return null;
}

@Override
public String updateEmployee(Employee employee) {
[Link]("Employee "+[Link]()+" Updated
Successfully from updateEmployee() method");
return "SUCCESS";
}

@Override
public String deleteEmployee(Employee employee) {
[Link]("Employee "+[Link]()+" Deleted
Successfully");
return "SUCCESS";
}
}

[Link]
package [Link];

import [Link];
import [Link];

public class LoggingAspect {


public void before([Link] joinPoint){
[Link]("Before
"+[Link]().getName()+" Method Execution");
}
public void after([Link] joinPoint){
[Link]("After
"+[Link]().getName()+" Method Execution");
}
public void afterReturning([Link] joinPoint,
Object result){
[Link]("After Returning "+result+" from
"+[Link]().getName()+" Method");
}
public void around(ProceedingJoinPoint proceedingJoinPoint){
[Link]("Before
"+[Link]().getName()+" execution from
AroundAdvice");
try {
[Link]();
} catch (Throwable e) {
[Link]();
}
[Link]("After
"+[Link]().getName()+" execution from
AroundAdvice");
}
public void afterThrowing(JoinPoint joinPoint, Throwable
throwable){
[Link]("After Throwing "+throwable+" from
"+[Link]().getName());
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import
[Link];

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("[Link]");
Employee employee = (Employee)
[Link]("employee");
EmployeeService employeeService = (EmployeeService)
[Link]("employeeService");
/*
String message = "";
try {
message = [Link](employee);
} catch (Exception e) {

}
[Link](message);
*/
//[Link](111);

//[Link](employee);

}
}

[Link]
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:aop="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
<bean id="employee" class="[Link]">
<property name="eno" value="111"/>
<property name="ename" value="Durga"/>
<property name="esal" value="50000"/>
<property name="eaddr" value="Hyd"/>
</bean>
<!-- Target -->
<bean id="employeeService"
class="[Link]"/>

<!-- Aspect -->


<bean id="loggingAspectBean"
class="[Link]"/>

<aop:config>
<aop:aspect id="loggingAspect" ref="loggingAspectBean">
<aop:pointcut id="employeePointcut"
expression="execution(*
[Link].*(..))"/>
<aop:before method="before"
pointcut-ref="employeePointcut"/>
<aop:after method="after"
pointcut-ref="employeePointcut"/>
<aop:after-returning method="afterReturning"
pointcut-ref="employeePointcut" returning="result"/>
<aop:around method="around"
pointcut-ref="employeePointcut"/>
<aop:after-throwing method="afterThrowing"
pointcut-ref="employeePointcut" throwing="throwable"/>
</aop:aspect>

</aop:config>
</beans>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>springaopapp05</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>

<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectj-tools</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.19</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.19</version>
</dependency>

</dependencies>

</project>

@AspectJ Annotations Style Approach:


—-------------------------------
Spring Framework Supporting annotations to support AspectJ implementations
in the form of “[Link]” package.

Spring AspectJ AOP implementation provides the following annotations.

1. @Aspect
2. @Pointcut
3. @Before
4. @After
5. @AfterReturning
6. @Around
7. @AfterThrowing

Note: To activate all the AOP AspectJ annotations in spring applications


we have to use the following tag in the Spring configuration file.

<aop:aspectj-autoproxy/>

EX:
[Link]
package [Link];

public class Account {


private String accNo;
private String accHolderName;
private String accType;
private double balance;

public String getAccNo() {


return accNo;
}

public void setAccNo(String accNo) {


[Link] = accNo;
}

public String getAccHolderName() {


return accHolderName;
}

public void setAccHolderName(String accHolderName) {


[Link] = accHolderName;
}

public String getAccType() {


return accType;
}

public void setAccType(String accType) {


[Link] = accType;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


[Link] = balance;
}
}

[Link]
package [Link];

import [Link];
import [Link];

public interface TransactionService {


public String withdraw(Account account, int withdrawAmount)throws
InsufficientFundsException;
}

[Link]
package [Link];

import [Link];
import [Link];

public class TransactionServiceImpl implements TransactionService{

@Override
public String withdraw(Account account, int withdrawAmount) throws
InsufficientFundsException {
[Link]("from withdraw() method , Transaction
Started");
String status = "";
if([Link]() > withdrawAmount){
double totalbalance = [Link]() -
withdrawAmount;
[Link](totalbalance);
[Link]("From withdraw() method, transaction
Completed");
status = "SUCCESS";
}else{
status = "FAILURE";
throw new InsufficientFundsException("Funds Are Not
Sufficient in Your Account");
}
return status;
}
}

[Link]
package [Link];

public class InsufficientFundsException extends Exception{


public InsufficientFundsException(String errorDescription) {
super(errorDescription);
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;

@Aspect
public class TransactionAspect {
@Before("execution(*
[Link].*(..))")
public void before(JoinPoint joinPoint){
Object[] args = [Link]();
Account account = (Account) args[0];
[Link]("Before Advice : Initial Balance :
"+[Link]());
}
@After("execution(*
[Link].*(..))")
public void after(JoinPoint joinPoint){
Object[] args = [Link]();
Account account = (Account) args[0];
[Link]("After Advice : Total Balance :
"+[Link]());
}
@AfterReturning(pointcut = "execution(*
[Link].*(..))", returning =
"results")
public void afterReturning(JoinPoint joinPoint, String results){
Object[] args = [Link]();
Account account = (Account) args[0];
[Link]("After Returning Advice : Transaction
Status : "+results);
}

@Around("execution(*
[Link].*(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) {
[Link]("Around Advice : Before
"+[Link]().getName()+" Method Execution");
String status = "";
try {
status = (String) [Link]();
} catch (Throwable e) {

}
[Link]("Around Advice : After : Transaction Status
: "+status);
}
@AfterThrowing(pointcut = "execution(*
[Link].*(..))", throwing =
"exception")
public void afterThrowing(JoinPoint joinPoint,
InsufficientFundsException exception){

[Link]("After Throwing Advice : Exception :


"+[Link]().getName()+" In the Transaction :
"+[Link]());
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("[Link]");
Account account = (Account)
[Link]("account");
TransactionService transactionService = (TransactionService)
[Link]("transactionService");
try {
[Link](account, 50000);
} catch (InsufficientFundsException e) {

}
}
}

[Link]
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:aop="[Link]
xmlns:context="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
[Link]

[Link]

<aop:aspectj-autoproxy/>
<bean id="account" class="[Link]">
<property name="accNo" value="abc123"/>
<property name="accHolderName" value="Durga"/>
<property name="accType" value="Savings"/>
<property name="balance" value="25000"/>
</bean>
<bean id="transactionService"
class="[Link]"/>
<bean id="transactionAspect"
class="[Link]"/>
</beans>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>springaopapp06</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>

<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.9</version>
</dependency>

<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectj-tools</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.19</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.19</version>
</dependency>
</dependencies>

</project>

======================================================

Common questions

Powered by AI

Challenges in implementing AOP in large-scale applications include complexity in managing numerous aspects and ensuring they don't conflict or overlap, leading to unexpected behavior during aspect weaving. Additionally, debugging can become challenging as the flow of execution is not straightforward. Mitigation strategies involve rigorous aspect design and modularization to maintain clear boundaries between aspects. Using sophisticated documentation and comprehensive testing tools to track aspect interactions can also help. Furthermore, integration with development methodologies that emphasize clarity in aspect application points, such as Pointcuts and JoinPoints, aids in preventing chaos .

In Spring AOP, a proxy enhances application architecture by sitting between the client and target objects, handling all method calls to add cross-cutting concerns without altering the target object's code. This allows advice to be dynamically applied to methods, encapsulating service logic handling away from business logic. The proxy thus enables modularization of concerns and enhances separation of duties within an application. It provides a lightweight method of applying aspects, enhancing maintainability, testing, and separation of concerns, crucial for complex enterprise applications where demands frequently shift .

In Spring AOP, advice is the implementation of an aspect, which includes the actual actions to be performed at certain joinpoints in the application. There are several types of advice: Before Advice is executed before a method call and is implemented via the MethodBeforeAdvice interface. After Advice is executed after a method returns a result, utilizing the AfterReturningAdvice interface. Throws Advice is triggered after a method throws an exception, while Around Advice surrounds a method invocation, allowing pre and post-processing with the MethodInterceptor interface. Each type of advice can enhance method execution without altering the core business logic by hooking into lifecycle events of a method execution .

The declarative approach relies on XML configuration to define aspects, pointcuts, and advice, providing a centralized, albeit verbose, way of managing an application's cross-cutting concerns. It allows for clearly separated configuration from application code, which can be beneficial in large teams. The annotation-based approach uses annotations within the code, such as @Aspect and @Pointcut, directly aligning aspect definitions with business logic, which simplifies readability and reduces configuration overhead. This is typically more manageable for small to medium projects or where instant visual context for code behavior is desired. Both methods can be used effectively depending on project needs and team preferences .

ThrowsAdvice significantly improves error handling by allowing aspects to intercept and handle exceptions thrown by business methods. This centralizes exception handling, making it easier to manage and modify without altering business logic directly. A particularly beneficial application is in a movie booking service, where ThrowsAdvice can log exceptions when a runtime error like "Power Failure Occurred" during movie play execution ensures user feedback and prompt rectifications are managed gracefully, as seen in scenarios involving recovering failed transactions or notifying users of service interruptions .

The ProxyFactoryBean simplifies managing cross-cutting concerns by creating a dynamic proxy object that encapsulates the target object along with specified interceptors, such as advice components. This removes the need to hardcode aspects into business logic, allowing them to be applied transparently. This configuration requires listing advice components under 'interceptorNames' that determine how and when the advice applies to the target methods. This setup ensures a separation of concerns and decouples aspect management from core application configuration, essential for clean and maintainable enterprise architectures .

Aspect-Oriented Programming (AOP) separates services logic, such as authentication, logging, and transactions, from business logic making the business components clean and focused solely on business operations. These cross-cutting concerns are implemented as aspects, which can be applied across different points of an application, known as joinpoints. This separation allows services to be reused across multiple components without duplicating the code in each component, improving code reusability. Additionally, since the service logic is centralized in one location, any necessary changes can be made once and will propagate to all components using that service, significantly enhancing maintainability .

Static pointcuts determine advice execution based on static criteria such as method names or class types, using interfaces like NameMatchMethodPointCut. These are effective for consistently applying advice to specific methods or classes regardless of runtime conditions. In contrast, dynamic pointcuts evaluate runtime conditions, such as method arguments, to decide whether to execute advice, exemplified by DynamicMethodMatcherPointCut. Dynamic pointcuts are more effective when advice needs to be conditional based on runtime data, enabling more flexible and responsive aspect behaviors .

'Around advice' in AOP provides a comprehensive hook into the method execution cycle, allowing pre and post-execution logic application, as well as managing method execution. It effectively combines the capabilities of before and after advice, offering complete control over the method execution process. The MethodInterceptor interface allows the advice to execute code before and after the target methods, plus the option to alter the outcome or manage exceptions actively. This makes it uniquely powerful for implementing transaction management, logging, and dynamic checks, offering maximum flexibility and control over business processing .

In Spring AOP, a joinpoint is a point during execution, such as method call or field access, where an aspect can be applied. A pointcut is an expression that selects a set of joinpoints to apply advice. Advice contains the action invoked at the joinpoints specified by the pointcut. Their interaction is critical because it allows for precise application of aspects, ensuring that cross-cutting concerns like logging, transaction management, and security are implemented effectively without altering the core business logic, thereby maintaining separation of concerns .

Spring AOP:
—----------
In general, in enterprise applications, we will prepare the applications by
using Object orientation
AOP is a methodology or a set of rules and regulations or a set of
conventions which are applied on the Object oriented Progr
AOP Terminology:
—----------------
1. Aspect
2. Advice
3. Joinpoint
4. Pointcut
5. Target
6. Proxy
7. Weaving
8. Introduction
Weaving:
Weaving is the process of applying aspects on the target
objects in Proxy
objects.
Introduction:
An introduction pro
Before Advice:
—---------------
Before Advice will have the Aspect implementation and it will be executed
just before the Bus
Where Object[] is representing parameters of the Business method.
Where Object [Third parameter] is representing Target objec
AroundAdvice:
—------------
This advice will be executed before and after the business method execution.
It is the combinatio
Static pointcut:
Static Pointcut defines the advice that is always executed.In Spring
applications we will define static poin
</bean>
Perl5RegexprMethodPointCut and JdkRegexMethodPointCut are able to provide
advice by matching the provided regular exp
EXample on Before Advice:
Employee.java
package com.durgasoft.beans;
public class Employee {
private int eno;
private String

You might also like