Spring-Spring AOPNo Comments

In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework.

Common AspectJ annotations :

  1. @Before – Run before the method execution
  2. @After – Run after the method returned a result
  3. @AfterReturning – Run after the method returned a result, intercept the returned result as well.
  4. @AfterThrowing – Run after the method throws an exception
  5. @Around – Run around the method execution, combine all three advices above.
  • Project Dependencies

To enable AspectJ, you need aspectjrt.jar, aspectjweaver.jar and spring-aop.jar. See following Maven pom.xml file.

AspectJ supported since Spring 2.0
This example is using Spring 3, but the AspectJ features are supported since Spring 2.0.

pom.xml :

  • Spring Beans

Normal bean, with few methods, later intercept it via AspectJ annotation.

  • Enable AspectJ

In Spring configuration file, put <aop:aspectj-autoproxy />, and define your Aspect (interceptor) and normal bean.

File : Spring-Customer.xml

  • AspectJ @Before

In below example, the logBefore() method will be executed before the execution of customerBo interface, addCustomer() method.

Note
AspectJ “pointcuts” is used to declare which method is going to intercept, and you should refer to this Spring AOP pointcuts guide for full list of supported pointcuts expressions.

File : LoggingAspect.java

Run it

Output

  • AspectJ @After

In below example, the logAfter() method will be executed after the execution of customerBo interface, addCustomer()method.

File : LoggingAspect.java

Run it

Output

  • AspectJ @AfterReturning

In below example, the logAfterReturning() method will be executed after the execution of customerBo interface, addCustomerReturnValue() method. In addition, you can intercept the returned value with the “returning” attribute.

To intercept returned value, the value of the “returning” attribute (result) need to be same with the method parameter (result).

File : LoggingAspect.java

Run it

Output

  • AspectJ @AfterReturning

In below example, the logAfterThrowing() method will be executed if the customerBo interface, addCustomerThrowException() method is throwing an exception.

File : LoggingAspect.java

Run it

Output

  • AspectJ @Around

In below example, the logAround() method will be executed before the customerBo interface, addCustomerAround()method, and you have to define the “joinPoint.proceed();” to control when should the interceptor return the control to the original addCustomerAround() method.

File : LoggingAspect.java

Run it

Output

  • Conclusion

It’s always recommended to apply the least power AsjectJ annotation. It’s rather long article about AspectJ in Spring. for further explanations and examples, please visit the reference links below

 

 

 


Be the first to post a comment.

Add a comment