Gangmax Blog

AOP of Spring Boot

Today I tried the AOP feature of Spring Boot.

Here is the example class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Aspect
@Configuration
public class DemoControllerAspect {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("execution(* com.demo.controller.DemoController.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();

joinPoint.proceed();

long timeTaken = System.currentTimeMillis() - startTime;
logger.info("-------Time Taken by {} is {}", joinPoint, timeTaken);
}
}

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