Tuesday, August 12, 2014

Spring AOP POJO Way

In Spring pure POJO way of defining aspects we can convert any POJO as aspects. The POJO itself does not knows that it is being used as Aspect.
Write a pure POJO class
PojoHelloWorldDecorator
public class PojoHelloWorldDecorator {
    // Message we intend to print before entering

    public void beforeprinteMessage() {
        System.out.println("Enter in printMessage");
    }
    // Message we intend to print after exiting
    public void afterprintMessage() {
        System.out.println("Exit from printMessage");
    }
}
Now register this aspect in configuration xml
<!-- Register the POJO based Advice --> 
<bean id="pojoHelloWorldDecorator" class="PojoHelloWorldDecorator" />
   <aop:config>
     <aop:aspect id="helloWorldAspect" ref="pojoHelloWorldDecorator">
       <aop:before method="beforeprinteMessage" pointcut="execution(* print*(..))" />
       <aop:after-returning method="afterprintMessage" pointcut="execution(* print*(..))" />
     </aop:aspect>
   </aop:config>
Call the bean in the main method
String[] files = {"context.xml"};
ApplicationContext appContext = new ClassPathXmlApplicationContext(files);        
HelloWorld helloWorld = (HelloWorld)appContext.getBean("helloWorld");
helloWorld.printMessage();

More Articles on Spring

No comments:

Post a Comment