@Around annotation: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.




Maven configuration


Add the following pom.xml to your application, or add the jar files to your application.




Business interface and implementation


package org.camelcode;

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


package org.camelcode;

import org.springframework.stereotype.Service;

@Service("bookService")
public class BookServiceImpl implements BookService {

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


Spring's application context


<aop:aspectj-autoproxy /> tells the spring container to search for the annotated classes.




@Around aspect


Around advice runs "around" a matched method execution. It has the oppertunity to do work before and after the method executes, it can also determine when, how and even if the method actually gets to execute at all.


package org.camelcode;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PerformanceAspect {

    @Pointcut("execution(* org.camelcode.BookServiceImpl*.*(..))")
    public void businessMethods() { }

    @Around("businessMethods()")
    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");
    }
}


References