Lafox.Net lafox.net
Spring Boot: custom annotation

Spring Boot: custom annotation

Example of custom annotation in Spring Boot.

First of all we need add AOP support to pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Now we can create annotation interface
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogTime {
}
In this code we created annotation interface. We can already use this annotation like:
@LogTime
public void calc() {
    doSomething();
}
Now we need to implement this custom annotation. Let's create annotation that calculate write in log function execution time. file. Let's start from easy case:
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogTimeImpl2 {

    @Around("@annotation(net.lafox.example.LogTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        return joinPoint.proceed();
    }

}
This is example of AOP (Aspect-Oriented Programming) style. Here present 3 main ideas of AOP:
@Aspect
By @Aspect annotation we mark the class that encapsulate some crosscutting expression.
@Around("@annotation(net.lafox.example.LogTime)")
By @Around annotation we explain that we liked to do something before and after executing function marked by @LogTime. By the way we also can use @Before and @After annotation.
return joinPoint.proceed()
This code will execute function marked by @LogTime. So, now we can calculate and log the time of function execution
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class LogTimeImpl {

    @Around("@annotation(net.lafox.example.LogTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long executionTime = System.currentTimeMillis() - start;
        log.info(joinPoint.getSignature() + " executed in " + executionTime + "ms");

        return proceed;
    }

}
1(source) 2(source)