March 23, 2011

Spring Framework 2.0 - Spring AOP Hello World Example

Complete the Spring Hello World example as in this post - http://www.javaissues.com/2011/03/spring-framework-20-hello-world-example.html

Download additional jars (aspectjrt.jar and aspectjweaver.jar) from the link here and copy them into the lib folder of the web application.

1) Create a Java class, MyAdvice.java as below,

package info.icontraining.spring;

public class MyAdvice {

   public void myBeforeMethod() {
      System.out.println("Before Execution");
   }
 
   public void myAfterMethod() {
      System.out.println("After Execution");
   }
}

2) Configure the MyAdvice bean in the Spring configuration file, applicationContext.xml

<bean id="myAdvice" class="info.icontraining.spring.MyAdvice" />

3) Configure the AOP configuration in the Spring configuration file, applicationContext.xml below the MyAdvice bean configuration

<aop:config>
   <aop:aspect ref="myAdvice">
       <aop:before method="myBeforeMethod" 
          pointcut="execution (* *.sayGreeting())" />
       <aop:after-returning method="myAfterMethod" 
          pointcut="execution (* *.sayGreeting())" />
   </aop:aspect>
</aop:config>

4) Access the springHelloWorld.jsp page - check the server console log to see if the advice methods are invoked.

http://localhost:8080/WebAppName/springHelloWorld.jsp

No comments:

Post a Comment