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.

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
("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:


and modify the XML schema details to look something like

<beans xmlns=""

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

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

No comments: