Friday, 16 September 2011

Using AspectJ’s @After Advice in your Spring App

Today’s blog demonstrates how to implement a simple after advice in your Spring application using the @After annotation. An after advice is where your advice code gets called after the join point in your point cut. I’ve previously blogged on the definitions AOP/AspectJ’s cryptic terms, but putting it simply, your advice code gets to run when a method whose signature meets some pre-defined pattern has finished running. Sets of methods whose signatures meet some pre-defined patterns are the point cuts.

The code below demonstrates a simple @After annotated advice that’s used to simply log when a matching method exits.

@Aspect
public class AfterAdvice {

 
private static Log logger = LogFactory.getLog(AfterAdvice.class);

 
@After("execution(* *.*(..))")
 
public void myAfterLogger(JoinPoint joinPoint) {
   
System.out.println("Okay - we're in the after handler...");

    Signature signature = joinPoint.getSignature
();
    String methodName = signature.getName
();
    String stuff = signature.toString
();
    String arguments = Arrays.toString
(joinPoint.getArgs());
    logger.info
("Write something in the log... Method: " + methodName + " with arguments "
       
+ arguments + "\nand the full toString: " + stuff + " has just been called");
 
}
}

The key points to note here is the @Aspect annotation, which declares this class as an AspectJ class and the @After annotation applied to the myAfterLogger(...) method. Of the two, the @After annotation is the most interesting because of its single attribute. This attribute is really a filter or specification that defines which methods in our application are part of this point cut, to which we’ll be applying this advice. The format of the string I’ve explained in a previous blog, so for now we’ll specify that this advice is applied after every method execution using:

  @After("execution(* *.*(..))")

In order for Spring to pick up the AspectJ annotations, you’ll need to add the following line to your Spring config file:

<aop:aspectj-autoproxy/$gt;

and modify the XML schema details to look something like

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">      

where the most important thing to note is the aop schema...

...and that’s all there is to it.

No comments: