Tuesday, August 12, 2014

Spring AOP in Programmatic Way

Spring 1.2 introduced ((AOP|Aspect Oriented Programming)) in a programmatic way. The AOP is applied by using ProxyFactory class. The factory class is provided with both the advice and the taregt.
Let's write an advice which will print a message before and after a HelloWorld program. Let's assume HelloWorld has a printMessage function.

HelloWorldDecorator

//Notice that MethodInterceptor comes from AOP alliance packages and

//not for spring framework. Spring has used the AOP alliance standards
//whereever possible
public class HelloWorldDecorator implements MethodInterceptor{

   public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    System.out.print("OyeJava says ");
    Object obj = methodInvocation.proceed();
    System.out.println(" I am here");
    return obj;
  }

Now modify the main method so that we use the proxy factory to apply AOP

String[] files = {"context.xml"};
ApplicationContext appContext = new ClassPathXmlApplicationContext(files);

HelloWorld helloWorld = (HelloWorld)appContext.getBean("helloWorld");
    
//Create the proxy factory class
ProxyFactory pf = new ProxyFactory();
    
//Add the advice to it
pf.addAdvice(new HelloWorldDecorator());

//Set the target class
pf.setTarget(helloWorld);

//Get the proxy back
HelloWorld helloWorldProxy = (HelloWorld)pf.getProxy();
    
//Notice the difference between outputs.
helloWorldProxy.printMessage();    
helloWorld.printMessage();

Spring supports the following advice with the mentioned interfaces:
  • Before – org.springframework.aop.MethodBeforeAdvice
  • After returning – org.springframework.aop.AfterReturningAdvice
  • Around – org.aopalliance.intercept.MethodInterceptor
  • Throws – org.springframework.aop.ThrowsAdvice
  • Introduction – org.springframework.aop.IntroductionInterceptor

No comments:

Post a Comment