Spring AOP (Aspect Oriented Programming) Example

With this tutorial we will see how to use Aspect Oriented Programming in Spring Framework. AOP is used in the Spring Framework to provide declarative enterprise services. It is also used to allow users to implement custom aspects, complementing their use of OOP with AOP.

We will demonstrate how to create and apply some central AOP concepts. In short we will create all types of advices, we will use a pointcut and an advisor over an advice and we will check on some special features of Spring in interceptors and proxy beans.

Our preferred development environment is Eclipse. We are using Eclipse Kepler version. We are also using Spring version 3.2.8 and the JDK 1.6.

Make sure you have the list of required jar files in your classpath.
Create an Advice

In AOP the Advice is an action taken before or after a method execution. There are different types of advice, such as around, before and after advice. Below we introduce all types of advice and show an example for each one of them.

AOPService.java class is the class whose methods will be intercepted by the advices


Before Advice

Before Advice executes before a method execution, but it does not have the ability to prevent execution flow proceeding to the method execution unless the method throws an exception. Our class has to implement the interface MethodBeforeAdvice.


The advice bean must be defined in Spring configuration file. In addition, a proxy object must be created, of ProxyFactoryBean type. The proxy bean has a target property. Its value is a reference to the bean whose methods will be intercepted. It also has an interceptorNames property. The property value is a list of bean names that represent the advices that will be applied on this proxy/target object.


We must load the aopServiceProxy bean in TestAOP.java in order to run the application, as shown below:


As a result, the before(Method method, Object[] args, Object target) method of the AOPBeforeMethod Advice is invoked before the simpleService‘s methods execution.



After Returning Advice

After returning advice is the Advice to be executed after a method execution completes normally: for example, if a method returns without throwing an exception. The class has to implement the interface AfterReturningAdvice.


We add the new bean in aopContext.xml, following the same steps as above.


Now, after running TestAOP.java class again we can see that the afterReturning(Object returnValue, Method method, Object[] args, Object target) method of AOPAfterReturningMethod advice is executed after the AOPService‘s methods’ execution.



After Throwing Advice

After throwing Advice is the Advice to be executed if a method exits by throwing an exception. The class has to implement the ThrowsAdvice interface.


We add the new bean in aopContext.xml


Now, after running the example again we can see that only the isValidNameLength() method is being intercepted by the AOPAfterThrowingExceptionMethod.



Around Advice

Around advice is the 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. The class has to implement the interface MethodInterceptor.



When running the application with the AOPARoundMethod advice we can see that it intercepts all methods of simpleService.



Create a Pointcut and an Advisor

The Pointcut indicates which method should be intercepted whereas the Advisor groups the Advice and the Pointcut into a single unit, and passes it to a proxy factory object.

There are two types of Pointcuts, the one that matches a method by its name and the one that matches a method using a regular expression pattern. Let’s see how both types of Pointcuts can be used.

Pointcut matching a name

In order to create a new Pointcut that will match a method by its name, we have to define it as a bean of NameMatchMethodPointcut type in aopContext.xml. In its property mappedName, the value to be set is the name of the method that will be intercepted. Here, we will intercept printAnyMessage(String msg) method.

We must also define the advisor as a bean of DefaultPointcutAdvisor type, here aopServiceBean bean. Its properties are pointcut; advice and their values are references to the beans of the advice and the pointcut that will be used.

Finally, in aopServiceProxy bean we must replace the AOPARoundMethod value of interceptorNames property with the aopServiceBean.


We run the TestAOP.java again. Now, only the printAnyMessage(String msg) method is being intercepted.



Alternatively, we can use the NameMatchMethodPointcutAdvisor, to combine both pointcut and advisor bean definitions in one bean, as shown below:




Pointcut matching a regex

Now, in order to create a pointcut that matches the method to be intercepted with a regular exression, we must define a new bean of RegexpMethodPointcutAdvisor type. The specific type of advisor has two properties. The patterns property holds a list of the patterns that are used for selecting the methods by their names that will be intercepted and applied the advice code. Here, in regexAdvisor we have used the *sblog* pattern, so again the printAnyMessage(String msg) method will be intercepted. The advice property holds a reference to the bean of the advice.


After running TestAOP.java class again we can see that only the method whose name matches the pattern *sblog* is being intercepted by the advice. The result is shown below:



AOP interceptors sequence

Now, let’s see how the sequence of the values in interceptorNames property of the proxy object can affect the sequence in which the advices intercept the methods. We need to create a new Around method advice, AOPARoundMethod.java class and add it to aopContext.xml as shown below:



When running the application we can see that the around method advice whose bean is defined first in aopServiceProxy is the one that intercepts the methods first.



Now, let’s change the sequence of the interceptors in aopServiceProxy bean and see what happens:


Again, the first defined interceptor is the one that intercepts the methods first:



AOP auto proxy creators

An interesting feature of Spring is that it provides two auto proxy creators, so that we can create proxies for our beans automatically.


The first auto proxy creator Spring provides is the BeanNameAutoProxyCreator that automatically creates AOP proxies for beans with names matching literal values or wildcards. In order to use it we must define it in aopContext.xml. This creator exposes two properties for us to configure. The first property is beanNames and its value is a list of regular expressions matching the Spring bean names (ids) to be proxied. The second property is interceptorNames and its value is a list of the advisors (Spring bean ids) that will be used.


Now we can load the aopServiceBean in TestAOP.java class, without having to know if this bean has a proxy object or not. The BeanNameAutoProxyCreator will load the proxy.





The second auto proxy creator Spring provides is the DefaultAdvisorAutoProxyCreator that automatically applies advisors in the current aopContext.xml, without the need to include specific bean names in the auto-proxy advisor’s bean definition. In order to use it we must specify a DefaultAdvisorAutoProxyCreator bean definition in aopContext.xml. Then we must specify any number of advisors in the same or related configuration files. The DefaultAdvisorAutoProxyCreator will automatically evaluate the pointcut contained in each advisor, to see what (if any) advice it should apply to each object.


After running TestAOP.java class again the result is shown below:



Thanks for your reading. Please do not forget to leave a comment.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.