Gangmax Blog

自由之思想,独立之精神

AOP of Spring Boot

Today I tried the AOP feature of Spring Boot.

Here is the example class.

1
@Aspect
2
@Configuration
3
public class DemoControllerAspect {
4
5
    private Logger logger = LoggerFactory.getLogger(this.getClass());
6
7
    @Around("execution(* com.demo.controller.DemoController.*(..))")
8
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
9
        long startTime = System.currentTimeMillis();
10
11
        joinPoint.proceed();
12
13
        long timeTaken = System.currentTimeMillis() - startTime;
14
        logger.info("-------Time Taken by {} is {}", joinPoint, timeTaken);
15
    }
16
}

This AOP aspect writes a logging line for each web request handled by the “DemoController” class.

Refer here and here.

Notes:

  1. The offical document of String AOP can be found here. The pointcut definition can be used in Spring boot as well.

  2. Make sure the aspect definition class can be scanned by Spring, otherwise it won’t take effect. Here is a post about how Spring Boot does the component scanning.

Comments