In this article, we will discuss after advice in detail. This is basically intercepted after the successful execution of method/s.
We will implement three different approaches
- Implements AfterReturningAdvice interface
- Using pointcut expression (XML Configurarion)
- Using AspectJ Annotations i.e.; (@Aspect / @AfterReturning)
Technology Used
- Java 1.7
- Eclipse Kepler IDE
- Maven 3.0.4
- Spring-4.0.0-RELEASE
- AspectJ
Mavenize or download required jars
Add Spring-4.0.0 dependencies to the pom.xml
<dependencies> <!-- Spring 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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- AspectJ dependencies --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${org.aspectj.version}</version> </dependency> </dependencies>
Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath
- spring-core-4.0.0-RELEASE
- spring-context-4.0.0-RELEASE
- spring-beans-4.0.0-RELEASE
- spring-aop-4.0.0-RELEASE
- spring-expression-4.0.0-RELEASE
- commons-logging-1.1.1
- aopalliance-1.0
- aspectjrt-1.7.4
- aspectjweaver-1.7.4
Let’s see coding in action
Create interface & classes for employee with their business methods to be exposed
Employee Service interface
Interface with five methods with simple CRUD like operations for employee bean. All methods inside employee interface are self explanatory
IEmployeeService.java
package com.spring.series.aop.service; public interface IEmployeeService { // simple CRUD operations for employee service public int createEmployee(String employeeDetails); public void getEmployee(int employeeId); public void updateEmployee(int employeeId); public void deleteEmployee(int employeeId); public void getAllEmployee(); }
Employee Service Provider class
Implementation of the above employee interface with standard sysout’s to print & study the flow of execution with advices
EmployeeServiceProvider.java
package com.spring.series.aop.service; public class EmployeeServiceProvider implements IEmployeeService { @Override public int createEmployee(String employeeDetails) { System.out.println("createEmployee : adds new employee and returns unique employee ID"); return 0001; } @Override public void getEmployee(int employeeId) { System.out.println("getEmployee : list employee details based on the employee ID"); } @Override public void updateEmployee(int employeeId) { System.out.println("updateEmployee : updates employee details based on the employee ID"); } @Override public void deleteEmployee(int employeeId) { System.out.println("deleteEmployee : deletes employee based on the employee ID"); } @Override public void getAllEmployee() { System.out.println("getAllEmployee : lists all employee details"); } }
Let’s discuss different approaches for after returning advice
Approach 1: creating advice class implementing standard available interfaces in Spring framework
Create after returning advice class implementing org.springframework.aop.AfterReturningAdvice and one more method for pointcut expression
AfterReturningAdviceInterceptor.java
package com.spring.series.aop.advice; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterReturningAdviceInterceptor implements AfterReturningAdvice { @Override public void afterReturning(Object returnValue, Method method,Object args[],Object target) throws Throwable { System.out.println("******** AfterReturningAdvice : " + method.getName() + " ********"); } /** * this is method is invoked from the pointcut expression declared in the spring context xml */ public void afterReturningAdviceUsingPointcutExpression() { System.out.println("******** After Returning Advice using Pointcut Expression ********"); } }
Create Spring context root xml to declare beans
Three beans declared in the Spring configuration xml file
- employeeService bean for the target object for which advice needs to be applied
- afterReturningAdviceInterceptor bean for after returning advice
- employeeServiceProxy bean combining interceptors & target object for AOP proxy mechanism
SpringAOPContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- target business class --> <bean id="employeeService" class="com.spring.series.aop.service.EmployeeServiceProvider" /> <!-- after returning advice class --> <bean id="afterReturningAdviceInterceptor" class="com.spring.series.aop.advice.AfterReturningAdviceInterceptor" /> <!-- employee proxy for after advice --> <bean id="employeeServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <list> <value>com.spring.series.aop.service.IEmployeeService</value> </list> </property> <property name="interceptorNames"> <list> <value>afterReturningAdviceInterceptor</value> </list> </property> <property name="target"> <ref bean="employeeService" /> </property> </bean> </beans>
Note: Name of the Spring Bean Configuration file can be anything (not necessary to have SpringAOPContext.xml) and it’s your choice. But, in the enterprise application keep these file names appropriate to the business context. So that it will increase the readability of the application
Project Structure in Eclipse (Package Explorer view)
Test the Application that’s exactly …. Run it!
TestEmployee.java
package com.spring.series.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.series.aop.service.IEmployeeService; public class TestEmployee { public static void main(String[] args) { testAdvice(); } // test using ApplicationContext private static void testAdvice(){ // load the spring xml configuration file from classpath ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/aop/SpringAOPContext.xml"); // get bean using applicationContext IEmployeeService employeeService = (IEmployeeService) applicationContext.getBean("employeeServiceProxy"); // employeeServiceProxy/employeeService // invoke business methods of EmployeeService employeeService.createEmployee("dummy emp details"); employeeService.getEmployee(001); employeeService.updateEmployee(002); employeeService.deleteEmployee(003); employeeService.getAllEmployee(); } }
Note: getBean() method takes proxy bean as argument and not the target object
Output in console
Aug 03, 2014 7:52:39 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@766e119d: startup date [Sun Aug 03 19:52:39 IST 2014]; root of context hierarchy Aug 03, 2014 7:52:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [com/spring/series/aop/SpringAOPContext.xml] createEmployee : adds new employee and returns unique employee ID ******** AfterReturningAdvice : createEmployee ******** getEmployee : list employee details based on the employee ID ******** AfterReturningAdvice : getEmployee ******** updateEmployee : updates employee details based on the employee ID ******** AfterReturningAdvice : updateEmployee ******** deleteEmployee : deletes employee based on the employee ID ******** AfterReturningAdvice : deleteEmployee ******** getAllEmployee : lists all employee details ******** AfterReturningAdvice : getAllEmployee ********
This way advice is applied after successful execution of all business methods of EmployeeService, but what if we want to restrict the advice should be advised to some of the particular business methods with after returning advice.
Solution: Include <aop:config> tag with pointcut expression defining the regex in the Spring root configuration xml file
Approach 2: Using pointcut expression to limit the advice to be applied to few particular methods
Updated Spring Configuration file with <aop:config> tag
Pointcut expression: “execution(* com.spring.series.aop.service.*.get(..)”
This pointcut expression narrows the advice to be applied only to the execution of the above methods.
General syntax: execution(<return_type> <qualified.package.name>.<className>.<methodName>.(<arguments>)
So, below pointcut expression narrows only methods whose methodName starts with get and has any number of arguments inside any class but within package com.spring.series.aop.service
SpringAOPContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- target business class --> <bean id="employeeService" class="com.spring.series.aop.service.EmployeeServiceProvider" /> <!-- after returning advice class --> <bean id="afterReturningAdviceInterceptor" class="com.spring.series.aop.advice.AfterReturningAdviceInterceptor" /> <!-- pointcut expression for after returning advice --> <aop:config> <aop:aspect id="aspect" ref="afterReturningAdviceInterceptor"> <aop:pointcut id="pointcutExpression" expression="execution(* com.spring.series.aop.service.*.get*(..))" /> <aop:after-returning pointcut-ref="pointcutExpression" method="afterReturningAdviceUsingPointcutExpression" /> </aop:aspect> </aop:config> </beans>
Let re-run the test class with getBean() method taking target object as argument.
TestEmployee.java
package com.spring.series.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.series.aop.service.IEmployeeService; public class TestEmployee { public static void main(String[] args) { testAdvice(); } // test using ApplicationContext private static void testAdvice(){ // load the spring xml configuration file from classpath ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/aop/SpringAOPContext.xml"); // get bean using applicationContext IEmployeeService employeeService = (IEmployeeService) applicationContext.getBean("employeeService"); // employeeServiceProxy/employeeService // invoke business methods of EmployeeService employeeService.createEmployee("dummy emp details"); employeeService.getEmployee(001); employeeService.updateEmployee(002); employeeService.deleteEmployee(003); employeeService.getAllEmployee(); } }
Output in console
Aug 03, 2014 7:55:12 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@766e119d: startup date [Sun Aug 03 19:55:12 IST 2014]; root of context hierarchy Aug 03, 2014 7:55:12 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [com/spring/series/aop/SpringAOPContext.xml] createEmployee : adds new employee and returns unique employee ID getEmployee : list employee details based on the employee ID ******** After Returning Advice using Pointcut Expression ******** updateEmployee : updates employee details based on the employee ID deleteEmployee : deletes employee based on the employee ID getAllEmployee : lists all employee details ******** After Returning Advice using Pointcut Expression ********
If you see output, after returning advice is applied to the methods which are starting with get and taking any number of arguments
That’s not all; let’s move onto the next approach
Approach 3: Using AspectJ Annotations i.e.; (@Aspect / @AfterReturning)
Business interface and their implementation classes remain the same. Only difference with this approach is that, removing those few lines of configuration from spring XML file and replacing with simple AspectJ annotations.
Create a class annotated with @Aspect and advice methods with @AfterReturning annotation for after returning advice
AfterReturningAdviceAnnotation.java
package com.spring.series.aop.advice; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; @Aspect public class AfterReturningAdviceAnnotation { // execution(returnType qualified.package.name.classname.methodname(arguments)) @AfterReturning("execution(* com.spring.series.aop.service.*.get*(..))") public void afterAdviceUsingAnnotation() { System.out.println("******** After Returning Advice using Annotation ********"); } }
Note
- Now advice will be applied only to the methods whose starting name is get
- If we replace this “get*” with just wild card character (*) then all advice will be applied to all the methods of employee service class
Create Spring context root xml to declare beans and turn on AspectJ annotation
Three beans declared in the Spring configuration xml file
- employeeService bean for the target object for which advice needs to be applied
- afterReturningAdviceAspect bean for after returning advice which is annotated with @Aspect/@AfterReturning annotation
- <aop:aspectj-autoproxy /> to turn ON AspectJ annotation and automatically creating proxies
SpringAOPContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- target business class --> <bean id="employeeService" class="com.spring.series.aop.service.EmployeeServiceProvider" /> <!-- to turn aspectJ annotation --> <aop:aspectj-autoproxy /> <!-- Aspect : after returning advice using annotation --> <bean id="afterReturningAdviceAspect" class="com.spring.series.aop.advice.AfterReturningAdviceAnnotation" /> </beans>
Time to test the annotated application example
TestEmployee.java
package com.spring.series.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.series.aop.service.IEmployeeService; public class TestEmployee { public static void main(String[] args) { testAdvice(); } // test using ApplicationContext private static void testAdvice(){ // load the spring xml configuration file from classpath ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/aop/SpringAOPContext.xml"); // get bean using applicationContext IEmployeeService employeeService = (IEmployeeService) applicationContext.getBean("employeeService"); // employeeServiceProxy/employeeService // invoke business methods of EmployeeService employeeService.createEmployee("dummy emp details"); employeeService.getEmployee(001); employeeService.updateEmployee(002); employeeService.deleteEmployee(003); employeeService.getAllEmployee(); } }
Output in console
Aug 03, 2014 7:55:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@766e119d: startup date [Sun Aug 03 19:55:54 IST 2014]; root of context hierarchy Aug 03, 2014 7:55:55 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [com/spring/series/aop/SpringAOPContext.xml] createEmployee : adds new employee and returns unique employee ID getEmployee : list employee details based on the employee ID ******** After Returning Advice using Annotation ******** updateEmployee : updates employee details based on the employee ID deleteEmployee : deletes employee based on the employee ID getAllEmployee : lists all employee details ******** After Returning Advice using Annotation ********
This annotation states that advice annotated with @AfterReturning annotation is advised only to the methods whose starting letters are get*(..) inside any class taking any number of arguments but restricted within package com.spring.series.aop.service as attribute in the @ AfterReturning annotation
Note: to apply advice to all business methods of the employee service class using AspectJ annotation, remove restriction with just a simple wildcard character (*) à this way advice is applied to all methods of the employee service class.
Download project
Spring-AOP-After-Returning-Advice (4kB) Spring-AOP-After-Returning-Advice-using-Pointcut (4kB)
Read Also:
- Spring AOP: Aspect Oriented Programming
- Spring AOP: Before Advice
- Spring AOP: After (Finally) Advice
- Spring AOP: After Throwing Advice
- Spring AOP: Around Advice
Happy Coding !!
Happy Learning !!