20 Nisan 2012 Cuma

Intercepting a Spring bean method with Spring AOP

Spring can give us an ability to intercept a Spring Bean method easily. We can do some job before or after method proceeding. And also get the method return result and process it after the invokation.
Firstly we determine the method of a bean which will be intercepted. For example a Spring bean:

Let's say it has a sample method named sampleMethod. We should create a method interceptor which implements org.aopalliance.intercept.MethodInterceptor:
public class SampleInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
         methodInvocation.proceed();
    } 
}
And then let's define it as a bean:

Then a point cut for the sample method which extends org.springframework.aop.support.DynamicMethodMatcherPointcut:
public class SampleMethodPointCut extends DynamicMethodMatcherPointcut {
    private Class clazz;
    private String methodName;

    public SampleMethodPointCut (Class clazz, String methodName) {
        this.clazz = clazz;
        this.methodName = methodName;
    }

    public boolean matches(Method method, Class cls) {
        return (methodName.equals(method.getName()));
    }

    public boolean matches(Method method, Class cls, Object[] args) {
        return true;
    }

    public ClassFilter getClassFilter() {
        return new ClassFilter() {
            public boolean matches(Class cls) {
                return (cls == clazz);
            }
        };
    }
}

      
      

And then we should define our point cut advisor:

       
       

Finally we should define bean name auto proxy creator:
    
        
        
            
                sampleBean
            
        
        
            
                sendMethodSplitterAdvisor
            
        
    
Our sampleMethod of sampleBean will be cut by our sample interceptor :)