Writing First AspectJ Program in Spring : Chapter 26

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

In Spring AOP, 4 type of advices are supported :
  • Before advice – Run before the method execution
  • After returning advice – Run after the method returns a result
  • After throwing advice – Run after the method throws an exception
  • Around advice – Run around the method execution, combine all three advices above.

1. Setting up the project structure:

Launch your preferred IDE (I use STS) and Create New Java Project. And then create the file structure as shown below...

You need to download all the JARs that are in User Libraries "aspectJ-lib" and add them to the project’s class path. You can find these JARs here: Spring, Commons-logging, aspectjrt, aspectjweaver.

2. Writing our Logging Aspect:

package com.dineshonjava.sdnext.aop.tutorial.aspectJ;

public class LoggingAspect
        public void loggingAdvice()
    System.out.println("Advice run. Get method is called");

3. Configuring Spring AOP and @AspectJ support:

  <bean class="com.dineshonjava.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect"></bean>
   <aop:aspect id="loggingAspect" ref="loggingAspect">
        <aop:after method="..." pointcut="..."></aop:after>

Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. These two approaches have been explained in detail in the following.

1. XML Schema based : Aspects are implemented using regular classes along with XML based configuration.

2. @AspectJ based : @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

No comments:

Post a Comment