spring aop 和控制器的启动问题

spring boot problems with aop and controller

当我使用 spring 引导时,aop 无法对注释控制器有效,我该如何最好地做到这一点?

@Aspect
@Component
@Configuration
public class MethodStatisticsPointcutAspect {

    @Resource
    private CounterService counterService;

    // aop defined
    @Around("@annotation(com.xxx.xxx.metrics.annotation.MethodStatistics)")
    private void around(ProceedingJoinPoint pjp) {
        // do sth
    }
}

我的控制器是这样定义的:

@RestController
@RequestMapping("/usertest")
public class UserTestController {

    @RequestMapping("/test")
    @MethodStatistics
    String test() {
       // do sth
   }
}

我想使用aop管理器所有带有注解@MethodStatistics的方法,但是它根本无法与@controller一起使用~

spring(和spring-boot)中的运行时 aop 绑定只能插入 public 方法。如果你想插入一个受保护的、私有的或包受保护的方法,你必须使用 aspectj 代码编织器而不是 spring 实现的运行时代理。

我在自己的项目中偶然发现了这一点,直到我阅读了指出这一点的文档(我的方法受到保护)

来自文档:[http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html]

Due to the proxy-based nature of Spring’s AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn’t applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!

If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision.