Saturday, August 21, 2010

Spring: Creating Automatic Proxy And Applying Advice

Spring provides comprehensive Aspect Oriented Programming (AOP) support. Without going into details of Spring AOP, an Advice can be broadly defined as an action taken during execution of a method.

In my previous blog entry, I have explained hibernate interceptor which uses spring's proxy objects to intercept method execution. Similarly Spring facilitates AOP advice by creating a proxy to intercept method execution and then calling the advice logic.

Spring provides various advices types which can be applied around a method execution. Some examples are : Before Return Advice, After Return Advice, After Throwing Advice, After Finally Advice etc.

One way to automatically intercept method execution on one or more objects and then apply an advice is to use Spring's BeanNameAutoProxyCreator and Advice API.

Following is an example where we create an AfterReturningAdvice, which is called when a target bean's method returns successfully.


public class HibernateAdvice implements AfterReturningAdvice {

@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
}
}



And here is how above advice can be applied to a set of beans. In this example all methods of all the beans, whose name ends with Dao will have above advice applied.


<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames" value="*Dao"/>
<property name="interceptorNames">
<list>
<value>hibernateAdvice</value>
</list>
</property>
</bean>
<bean id="hibernateAdvice" class="com.example.HibernateAdvice"/>


Note that interceptorNames can be an advice type as shown above or an advisor. An advisor will allow more fine grained control on how a specific advice should be applied. (For example apply advice only on selected methods of a bean etc)
Promote your blog

No comments:

Post a Comment