aop和控制器的弹簧启动问题

时间:2015-07-09 03:49:16

标签: java controller spring-boot

当我使用弹簧启动时,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
   }
}

我希望使用带有注释@ MethodStatistics的所有方法的aop管理器,但它根本无法与@controller一起使用〜

1 个答案:

答案 0 :(得分:0)

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

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

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

  

由于Spring的AOP框架基于代理的特性,受到保护   根据定义,方法既不被拦截,也不用于JDK代理   (这不适用)也不适用于CGLIB代理(如果是这样的话)   技术上可行,但不建议用于AOP目的)。作为一个   结果,任何给定的切入点都将与公共方法相匹配   只有!

     

如果您的拦截需要包括受保护/私有方法甚至   构造函数,考虑使用Spring驱动的原生AspectJ编织   而不是Spring的基于代理的AOP框架。这构成了一个   不同模式的AOP使用具有不同的特性,所以一定要确定   在做出决定之前先让自己熟悉编织。

相关问题