Spring AOP – AspectJ Annotation Example

In my previous tutorial I have shown how to write Spring AOP using XML configuration and in this tutorial I am going to show you how to write Annotation based Spring AOP using @AspectJ. This example creates annotation examples with @Aspect, @Pointcut, @Before, @After, @Around, @AfterReturning, @AfterThrowing Advice. @AspectJ is a style to declare aspects in a Java class using annotation. @EnableAspectJAutoProxy annotation is used in Java configuration to enable @AspectJ. To work with spring AOP and @AspectJ support, we need to create a class annotated with @Aspect annotation. Inside @Aspect annotated class we can create our pointcut and using pointcut we can also create our advice. Spring AOP is used for different purposes such as logging, transaction management, handling with exception and validating return value of a method.

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. Such concerns are often termed crosscutting concerns in AOP literature.

More information can be found at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

AOP concepts

Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).

Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

Advice: action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.

Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default. Spring AOP only supports method execution join points for Spring beans, so you can think of a pointcut as matching the execution of methods on Spring beans. A pointcut declaration has two parts: a signature comprising a name and any parameters, and a pointcut expression that determines exactly which method executions we are interested in.

Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching.

Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.

AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Types of advice:
Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

After throwing advice: Advice to be executed if a method exits by throwing an exception.

After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Supported Pointcut Designators

Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions:

execution – for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP

within – limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)

this – limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type

target – limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type

args – limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types

@target – limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type

@args – limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)

@within – limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)

@annotation – limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation

Some examples of common pointcut expressions are given below.

the execution of any public method: execution(public * *(..))

the execution of any method with a name beginning with “set”: execution(* set*(..))

the execution of any method defined by the AccountService interface:

    execution(* com.xyz.service.AccountService.*(..))

the execution of any method defined in the service package:

    execution(* com.xyz.service.*.*(..))

the execution of any method defined in the service package or a sub-package:

execution(* com.xyz.service..*.*(..))

any join point (method execution only in Spring AOP) within the service package:

within(com.xyz.service.*)

any join point (method execution only in Spring AOP) within the service package or a sub-package:

within(com.xyz.service..*)

any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:

this(com.xyz.service.AccountService)

‘this’ is more commonly used in a binding form.

any join point (method execution only in Spring AOP) where the target object implements the AccountService interface:

target(com.xyz.service.AccountService)

‘target’ is more commonly used in a binding form.

any join point (method execution only in Spring AOP) which takes a single parameter, and where the argument passed at runtime is Serializable:

args(java.io.Serializable)

‘args’ is more commonly used in a binding form.

Note that the pointcut given in this example is different to execution(* *(java.io.Serializable)): the args version matches if the argument passed at runtime is Serializable, the execution version matches if the method signature declares a single parameter of type Serializable.

any join point (method execution only in Spring AOP) where the target object has an @Transactional annotation:

@target(org.springframework.transaction.annotation.Transactional)

‘@target’ can also be used in a binding form.

any join point (method execution only in Spring AOP) where the declared type of the target object has an @Transactional annotation:

@within(org.springframework.transaction.annotation.Transactional)

‘@within’ can also be used in a binding form.

any join point (method execution only in Spring AOP) where the executing method has an @Transactional annotation:

@annotation(org.springframework.transaction.annotation.Transactional)

‘@annotation’ can also be used in a binding form.

any join point (method execution only in Spring AOP) which takes a single parameter, and where the runtime type of the argument passed has the @Classified annotation:

@args(com.xyz.security.Classified)

‘@args’ can also be used in a binding form.

any join point (method execution only in Spring AOP) on a Spring bean named tradeService:

bean(tradeService)

any join point (method execution only in Spring AOP) on Spring beans having names that match the wildcard expression *Service:

bean(*Service)

AOP Proxies

Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies

Let’s now look at the below example on Annotation based Spring AOP.

Prerequisites

The following configurations are required in order to run the application

Eclipse Kepler
JDK 1.8
Tomcat 8
Have maven 3 installed and configured
Spring 4, AspectJ dependencies in pom.xml

Now we will see the below steps how to create a maven based project in Eclipse

Step 1. Create a maven based standalone project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-quickstart

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : spring-aop

Step 2. Modify the pom.xml file as shown below.

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Use below Java configuration class to enable @AspectJ support using @EnableAspectJAutoProxy

Step 5. Create below aop.properties file under src/main/resources directory for autowiring constructor arguments’ values

Step 6. Create below service class whose methods will be intercepted by the advices

Watch out in the above class how constructor arguments are autowired using properties values.

Step 7. Create below AopAdvice.java where each advice will be created

Step 7. Create @Before advice inside the AopAdvice.java

Step 8. Create below test class AopAdviceTest.java which will be executed for each advice testing

Step 9. Now run the above AopAdviceTest.java you will see below output in the console. You see here AopAdvice => executed Before advice is executed before each method of the service class.

Step 10. Now create @After advice inside the class AopAdvice class. So just put the below code inside AopAdvice class.

When you run the AopAdviceTest class you will see the below output in the console. You see here AopAdvice => executed After advice is executed after each method of the service class.

Step 11. Now create @AfterReturning advice inside the class AopAdvice class. So just put the below code inside AopAdvice class.

When you run the AopAdviceTest class you will see the below output in the console. You see here AopAdvice => executed AfterReturning advice is executed after returning from each method of the service class.

Step 12. Now create @AfterThrowing advice inside the class AopAdvice class. So just put the below code inside AopAdvice class. To let a method throw an exception also change the aop.name=roytuts.com as aop.name=ro in aop.properties file.

When you run the AopAdviceTest class you will see the below output in the console. You see here AopAdvice => executed AfterThrowing advice is executed after throwing exception from method isNameLengthValid() of the service class.

Step 13. Now create @Around advice inside the class AopAdvice class. So just put the below code inside AopAdvice class.

When you run the AopAdviceTest class you will see the below output in the console. You see here AopAdvice => executed Around advice :: before and AopAdvice => executed Around advice :: after are executed before executing & after returning from each method of the service class.

Now we will see how to create pointcuts and apply advice on pointcuts.

Step 14. Create below AopPointcut.java where pointcuts will be created and advice on pointcut will be applied.

Step 15. Now create below pointcut inside the class AopPointcut class. So just put the below code inside AopPointcut class.

Now you can apply any advice (i.e., @Before) or all advices (i.e., @Before, @After, @Around, @AfterReturning, @AfterThrowing) on the above pointcut.

When you run the AopAdviceTest class you will see the below output in the console.

Step 16. Now create below pointcut inside the class AopPointcut class. So just put the below code inside AopPointcut class.

Now you can apply any advice (i.e., @Before) or all advices (i.e., @Before, @After, @Around, @AfterReturning, @AfterThrowing) on the above pointcut.

When you run the AopAdviceTest class you will see the below output in the console.

Step 17. Now create below pointcut inside the class AopPointcut class. So just put the below code inside AopPointcut class.

Now you can apply any advice (i.e., @Before) or all advices (i.e., @Before, @After, @Around, @AfterReturning, @AfterThrowing) on the above pointcut as shown in the previous step and you can test the same.

As per your requirements you can create as many pointcuts as you wish but for this tutorial I think it was enough.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.