Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Simply putting it, it is just an interceptor to intercept some processes. For example: when a method is executed, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.
In Spring AOP, 4 types of advices are supported:
Before advice – Run before the method execution
After returning advice – Run after the method returns a result
After throwing advice – Run after the method throws an exception
Around advice– Run around the method execution, combine all three advices above.
Following is a simple example that shows how Spring AOP advice works.
Create a simple customer service class with few print methods for demonstration later.
File : Spring-Customer.xml – A bean configuration file
Spring AOP Advices
Now, attach Spring AOP advices to above customer service.
1. Before advice
It will execute before the method execution. Create a class which implements MethodBeforeAdvice interface.
In bean configuration file (Spring-Customer.xml), create a bean for BeforeMethod class, and a new proxy object named ‘customerServiceProxy‘.
‘target’ – Define which bean you want to hijack.
‘interceptorNames’ – Define which class (advice) you want to apply on this proxy /target object.
To use Spring proxy, you need to add CGLIB2 library. Add below in Maven pom.xml file.
Run it again, now you get the new customerServiceProxybean instead of the original customerService bean.
It will run the BeforeMethod’s before() method, before every customerService’s methods are executed.
2. After returning advice
It will execute after the method returns a result. After that, create a class that implements AfterReturningAdvice interface.
Bean configuration file
Run it again
It will run the AfterMethod’s afterReturning() method, after every customerService’s methods that returned result.
3. After throwing advice
It will execute after the method throws an exception. Create a class which implements ThrowsAdvice interface, and create an afterThrowing method to the IllegalArgumentException exception.
Bean configuration file
It will run the ThrowException’s afterThrowing() method, if customerService’s methods throw an exception.
4. Around advice
It combines all three advices above, and executes during method execution. Create a class which implements MethodInterceptor interface. You have to call the “methodInvocation.proceed();” to proceed on the original method execution, else the original method will not execute.
Bean Configuration file
Run it again,
In Conclusion every time a developer uses around method advice but we should identify our requirement and base on that we should use particular advice of Sping AOP.