Search code examples
javaspringspring-bootaopaspectj

Log controller with AspectJ


I have a Spring boot application, and I want to log some info what happens when a Controller method id invoked.

For some reason, my Aspect is not working.

Here is my @Component class annotated with @Aspect:

@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}

@Pointcut("execution(* *.*(..))")
protected void allMethod() {
}

@Before("controller()&& allMethod()")
public void logBefore(JoinPoint joinPoint) {
}

The logBefore method is not called, when any Controller method is called with REST.


Solution

  • Important: As you've stated you are using a Spring Boot setup, my assumption is that you've implemented the Spring AOP module instead of the "actual" AspectJ library. The difference is significant, as the implementation of AOP differs between them. Spring uses the AspectJ annotations to apply proxying, while AspectJ "weaves" the code into your application. In short, Spring AOP might be easier to implement, while AspectJ offers more fine-grained functionality (such as compile-time weaving). A comparison can be found here.

    I have tried out the configuration from the code snippet you provided in your post. The advice was invoked after I added several annotations:

    @SpringBootApplication
    // Be sure to add EnableAspectJAutoProxy and set proxyTargetClass to true
    @EnableAspectJAutoProxy(proxyTargetClass = true)
    public class DemoApplication {
      ...
    }
    
    // Be sure to add @Aspect and @Component
    @Component
    @Aspect
    public class DemoAop {
    
      private static Logger logger = LoggerFactory.getLogger(DemoAop.class);
    
      @Pointcut("within(@org.springframework.stereotype.Controller *)")
      public void controller() {
      }
    
      @Pointcut("execution(* *.*(..))")
      protected void allMethod() {
      }
    
      @Before("controller()&& allMethod()")
      public void logBefore(JoinPoint joinPoint) {
        logger.info("TEST");
      }
    
    }