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.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>spring-aop</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>spring-aop</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<aspectj.version>1.8.10</aspectj.version>
		<spring.version>4.3.4.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- AspectJ dependencies -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${aspectj.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjtools</artifactId>
			<version>${aspectj.version}</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

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

package com.roytuts.spring.aop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.roytuts.spring.aop")
@PropertySource(value = { "classpath:aop.properties" })
public class AspectConfig {
}

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

aop.id=1000
aop.name=roytuts.com
#aop.name=ro #for AfterThrowing test

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

package com.roytuts.spring.aop.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Service
@Component
public class AopService {
	private int aopId;
	private String aopName;
	@Autowired
	public AopService(@Value("${aop.id}") int aopId, @Value("${aop.name}") String aopName) {
		this.aopId = aopId;
		this.aopName = aopName;
	}
	public void printAopInfo() {
		System.out.println("------------------------------------");
		System.out.println("AopService => aopId: " + aopId + ", aopName: " + aopName);
		System.out.println("------------------------------------");
	}
	public void isNameLengthValid() {
		System.out.println("---------------------------------");
		if (aopName != null || !aopName.trim().isEmpty()) {
			if (aopName.trim().length() < 6 || aopName.trim().length() > 25) {
				throw new IllegalArgumentException(
						"AopService => Name must not be less than 3 chars and greater than 25 chars long!");
			} else {
				System.out.println("AopService => Name is valid!");
			}
		} else {
			throw new IllegalArgumentException("AopService => Name canot be null!");
		}
		System.out.println("----------------------------------");
	}
	public void printMsg(String msg) {
		System.out.println("------------------------------");
		System.out.println("AopService => Message: " + msg);
		System.out.println("-----------------------------");
	}
}

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

package com.roytuts.spring.aop.aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AopAdvice {
}

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

package com.roytuts.spring.aop.aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AopAdvice {
	@Before("execution(* com.roytuts.spring.aop.service.*.*(..))")
	public void logBefore() {
		System.out.println("AopAdvice => executed Before advice");
	}
}

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

package com.roytuts.spring.aop.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.roytuts.spring.aop.AspectConfig;
import com.roytuts.spring.aop.service.AopService;
public class AopAdviceTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.register(AspectConfig.class);
		applicationContext.refresh();
		AopService service = applicationContext.getBean(AopService.class);
		service.printAopInfo();
		service.isNameLengthValid();
		service.printMsg("Any message printing method");
		applicationContext.close();
	}
}

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.

AopAdvice => executed Before advice
------------------------------------
AopService => aopId: 1000, aopName: roytuts.com
------------------------------------
AopAdvice => executed Before advice
---------------------------------
AopService => Name is valid!
----------------------------------
AopAdvice => executed Before advice
------------------------------
AopService => Message: Any message printing method
-----------------------------

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

@After("execution(* com.roytuts.spring.aop.service.*.*(..))")
public void logAfter() {
	System.out.println("AopAdvice => executed After advice");
}

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.

------------------------------------
AopService => aopId: 1000, aopName: roytuts.com
------------------------------------
AopAdvice => executed After advice
---------------------------------
AopService => Name is valid!
----------------------------------
AopAdvice => executed After advice
------------------------------
AopService => Message: Any message printing method
-----------------------------
AopAdvice => executed After advice

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

@AfterReturning("execution(* com.roytuts.spring.aop.service.*.*(..))")
public void logAfterReturning() {
	System.out.println("AopAdvice => executed AfterReturning Advice");
}

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.

------------------------------------
AopService => aopId: 1000, aopName: roytuts.com
------------------------------------
AopAdvice => executed AfterReturning Advice
---------------------------------
AopService => Name is valid!
----------------------------------
AopAdvice => executed AfterReturning Advice
------------------------------
AopService => Message: Any message printing method
-----------------------------
AopAdvice => executed AfterReturning Advice

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.

@AfterReturning("execution(* com.roytuts.spring.aop.service.*.*(..))")
public void logAfterReturning() {
	System.out.println("AopAdvice => executed AfterReturning Advice");
}

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.

------------------------------------
AopService => aopId: 1000, aopName: ro
------------------------------------
---------------------------------
Exception in thread "main" java.lang.IllegalArgumentException: AopService => Name must not be less than 3 chars and greater than 25 chars long!
	at com.roytuts.spring.aop.service.AopService.isNameLengthValid(AopService.java:31)
	at com.roytuts.spring.aop.service.AopService$$FastClassBySpringCGLIB$$2749b33a.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)AopAdvice => executed AfterThrowing Advice

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

@Around("execution(* com.roytuts.spring.aop.service.*.*(..))")
public void logAround(ProceedingJoinPoint pjp) throws Throwable {
	System.out.println("AopAdvice => executed Around Advice :: before");
	pjp.proceed();
	System.out.println("AopAdvice => executed Around Advice :: after");
}

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.

AopAdvice => executed Around Advice :: before
------------------------------------
AopService => aopId: 1000, aopName: roytuts.com
------------------------------------
AopAdvice => executed Around Advice :: after
AopAdvice => executed Around Advice :: before
---------------------------------
AopService => Name is valid!
----------------------------------
AopAdvice => executed Around Advice :: after
AopAdvice => executed Around Advice :: before
------------------------------
AopService => Message: Any message printing method
-----------------------------
AopAdvice => executed Around Advice :: after

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.

package com.roytuts.spring.aop.aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AopPointcut {
}

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

// the execution of any method defined in the service package
@Pointcut("execution(* com.roytuts.spring.aop.service.*.*(..))")
public void service() {
}

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

@Before("service()")
public void logBefore() {
	System.out.println("AopPointcut => executed Before advice");
}
@After("service()")
public void logAfter() {
	System.out.println("AopPointcut => executed After advice");
}
@AfterReturning("service()")
public void logAfterReturning() {
	System.out.println("AopPointcut => executed AfterReturning Advice");
}
@AfterThrowing("service()")
public void logAfterThrowing() {
	System.out.println("AopPointcut => executed AfterThrowing Advice");
}
@Around("service()")
public void logAround(ProceedingJoinPoint pjp) throws Throwable {
	System.out.println("AopPointcut => executed Around Advice :: before");
	pjp.proceed();
	System.out.println("AopPointcut => executed Around Advice :: after");
}

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

AopPointcut => executed Around Advice :: before
AopPointcut => executed Before advice
------------------------------------
AopService => aopId: 1000, aopName: roytuts.com
------------------------------------
AopPointcut => executed Around Advice :: after
AopPointcut => executed After advice
AopPointcut => executed AfterReturning Advice
AopPointcut => executed Around Advice :: before
AopPointcut => executed Before advice
---------------------------------
AopService => Name is valid!
----------------------------------
AopPointcut => executed Around Advice :: after
AopPointcut => executed After advice
AopPointcut => executed AfterReturning Advice
AopPointcut => executed Around Advice :: before
AopPointcut => executed Before advice
------------------------------
AopService => Message: Any message printing method
-----------------------------
AopPointcut => executed Around Advice :: after
AopPointcut => executed After advice
AopPointcut => executed AfterReturning Advice

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

// any join point (method execution only in Spring AOP) within the service
// package or a sub-package
@Pointcut("within(com.roytuts.spring.aop.service..*)")
public void inService() {
}

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

@Before("inService()")
public void logBefore() {
	System.out.println("AopPointcut => executed Before advice");
}
@After("inService()")
public void logAfter() {
	System.out.println("AopPointcut => executed After advice");
}
@AfterReturning("inService()")
public void logAfterReturning() {
	System.out.println("AopPointcut => executed AfterReturning Advice");
}
@AfterThrowing("inService()")
public void logAfterThrowing() {
	System.out.println("AopPointcut => executed AfterThrowing Advice");
}
@Around("inService()")
public void logAround(ProceedingJoinPoint pjp) throws Throwable {
	System.out.println("AopPointcut => executed Around Advice :: before");
	pjp.proceed();
	System.out.println("AopPointcut => executed Around Advice :: after");
}

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

AopPointcut => executed Around Advice :: before
AopPointcut => executed Before advice
------------------------------------
AopService => aopId: 1000, aopName: roytuts.com
------------------------------------
AopPointcut => executed Around Advice :: after
AopPointcut => executed After advice
AopPointcut => executed AfterReturning Advice
AopPointcut => executed Around Advice :: before
AopPointcut => executed Before advice
---------------------------------
AopService => Name is valid!
----------------------------------
AopPointcut => executed Around Advice :: after
AopPointcut => executed After advice
AopPointcut => executed AfterReturning Advice
AopPointcut => executed Around Advice :: before
AopPointcut => executed Before advice
------------------------------
AopService => Message: Any message printing method
-----------------------------
AopPointcut => executed Around Advice :: after
AopPointcut => executed After advice
AopPointcut => executed AfterReturning Advice

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

// the execution of any public method
@Pointcut("execution(public * *(..))")
public void inPublic() {
}

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 *