Spring Boot + AOP

Spring Boot + AOP

2021, Sep 23    

Hướng dẫn sử dụng Spring AOP để xử lý cho annotation trong Spring Boot application

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
</dependencies>    
  • Tạo annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimeLogger {

  String value() default "";
}
  • Tạo class xử lý annotation
@Aspect
@Component
public class TimeLoggerAspectJ {

  @Pointcut("@annotation(timeLogger)")
  public void annotatedTimeLogger(TimeLogger timeLogger) {
  }

  @Around("annotatedTimeLogger(timeLogger)")
  public Object around(ProceedingJoinPoint joinPoint, TimeLogger timeLogger) throws Throwable {
    String value = timeLogger.value();
    long startTime = System.currentTimeMillis();

    try {
      return joinPoint.proceed();
    } finally {

      long processTime = System.currentTimeMillis() - startTime;
      log.info(String.format("Process [%s] in [%s]", value, processTime));
    }

  }
}
  • Thêm annotaion EnableAspectJAutoProxy để kích hoạt Aop
@EnableAspectJAutoProxy
@SpringBootApplication
public class AopApplication {

	public static void main(String[] args) {
		SpringApplication.run(AopApplication.class, args);
	}

}

Source code ở đây