public class LoggingBean implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice { public LoggingBean() { } public void afterThrowing(Method invokedMethod, Object[] parameters, Object invokedClass, Exception exp) { // do logging here after an exception } @Override public void before(Method invokedMethod, Object[] parameters, Object invokedClass) throws Throwable { // do logging here before method } @Override public void afterReturning(Object returnVal, Method invokedMethod, Object[] parameters, Object invokedClass) throws Throwable { // do logging here after method } }As you can see, you can use any values needed for logging from parameters of the methods (returnVal, invokedMethod, parameters, invokedClass).
Now we will introduce this bean to spring in a xml file. And we will also create a bean from BeanNameAutoProxyCreator for intercepting the requested beans with the above class.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="logger" class="LoggingBean"/> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <value>*Service</value> <value>*Client</value> </list> </property> <property name="interceptorNames"> <list> <value>logger</value> </list> </property> </bean> </beans>In the beanNames property, we are selecting which spring beans to apply the interceptor (in the example, we are applying the filter to the beans those names end with Service or Client) and in the interceptorNames property, we are selecting the interceptors.
That's all. You can now log your methods before and after execution, also after throwing an exception.
Ref: Spring BeanNameAutoProxyCreator JavaDoc
A Knol About Spring Aop
No comments:
Post a Comment