The Around advice runs 'around' a match method execution. It has the opportunity to do work both before and after the method executes, and the around advice can also determine whether the method actually gets to execute at all. Around advice is often used if you need to share state before and after a method execution in a thread-safe-manner (Starting and stopping a timer for example). For benchmark testing or performance testing for example. Always use the least powerful form of advice that meets your requirements. Do not use the around advice if simple before advice would do because the around advice is a performance hit.

The first parameter of the advice method must be of type ProceedingJoinPoint. Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute.




Maven configuration



Business interface and implementation


package org.camelcode;

public interface BookService {
    public void printBook(String book);
}


package org.camelcode;

public class BookServiceImpl implements BookService {

    public void printBook(String book) {
        System.out.println(book);
    }
}


Spring's application context



    
    

    
        
            

            

        
    



Around aspect


NOTE: It's crucial that you remember to include a call to the proceed() method. If you don't, then your advice will effectively block access to the advised method.

What's also interesting is that just as you can omit a call to the proceed() method to block access to the advised method, you can also invoke it multiple times from within the advice. One reason for doing this may be to implement retry logic to perform repeated attempts on the advised method should it fail.


package org.camelcode;

import org.aspectj.lang.ProceedingJoinPoint;

public class PerformanceAspect {

    public Object profile(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        System.out.println("Going to call method: " + pjp.getSignature());
        Object output = pjp.proceed();
        System.out.println("Method execution completed.");
        long elapsedTime = System.currentTimeMillis() - start;
        System.out.println("Method execution time: " + elapsedTime + " milliseconds.");
        return output;
    }
}


Helper class

package org.camelcode;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String...args){
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        BookService bookService = (BookService)context.getBean("bookService");
        bookService.printBook("camelcode.org");
    }
}


Output

Going to call method: void org.camelcode.BookService.printBook(String)
camelcode.org
Method execution completed.
Method execution time: 2 milliseconds.


References