Site icon Experiences Unlimited

Execute around Aspect with @annotation pointcut in Spring Boot

Aspect oriented programming (AOP) is a programming model where we write independently executable code which adds additional behavior to the existing code without modifying the existing code.

Wikipedia defines AOP as:

In this article, I will show you how to execute certain code around the execution of a method which means I would execute some code before the target method is called and some code after the target method has returned the value.

This extra code that executes around a target method is called an Aspect and when this code needs to be executed is called an Advice. There are different types of advice based on when we want our code to be executed:

Identifying the target method is done by writing an expression which we call a pointcut expression. There are different ways of identifying the target method:

In this article, we will identify the methods to be enhanced using an annotation.

For a detailed explanation on AOP with Spring I would highly recommend you to read this documentation from Spring.

Updating Maven dependency

We will add the following dependency to our pom.xml for adding the required AOP libraries:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Defining the Aspect
@Slf4j
@Aspect
@Component
public class TimerAspect {

    @Around("@annotation(Timer)")
    private Object recordTimeTaken(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object value = pjp.proceed();
        long endTime = System.currentTimeMillis();
        log.debug("Time taken for method {} is {} ms", 
            pjp.toShortString(), (endTime - startTime));
        return value;
    }
}

Important parts in the above code:

Defining the @Timer annotation

The new annotation we added @Timer is the key to identifying the target methods which need to be enhanced. The annotation is defined as:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Timer {
}
Enable AOP in Spring Boot

We will use the @EnableAspectJAutoProxy annotation to enable AOP support in our Spring Boot app.

Identifying the target methods

The methods which need to use the new aspect added will be annotated with @Timer annotation.

public class MyClass{
    @Timer
    public void myMethod(){
    }
}
Exit mobile version