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
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:aspect id="helloWorldAspect" ref="pojoHelloWorldDecorator">
       <aop:before method="beforeprinteMessage" pointcut="execution(* print*(..))" />
       <aop:after-returning method="afterprintMessage" pointcut="execution(* print*(..))" />
Call the bean in the main method
String[] files = {"context.xml"};
ApplicationContext appContext = new ClassPathXmlApplicationContext(files);        
HelloWorld helloWorld = (HelloWorld)appContext.getBean("helloWorld");

More Articles on Spring

No comments:

Post a Comment