【问题标题】:spring boot problems with aop and controlleraop和控制器的spring boot问题
【发布时间】:2015-07-09 03:49:16
【问题描述】:

当我使用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 manager,但是它根本无法使用@controller~

【问题讨论】:

  • 欢迎来到Stack Overflow。我不确定你的问题是什么,也不确定你有什么问题。

标签: java controller spring-boot


【解决方案1】:

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使用模式不同,所以一定要 在做出决定之前先让自己熟悉编织。

【讨论】:

    猜你喜欢
    • 2016-08-15
    • 2015-11-28
    • 1970-01-01
    • 2017-03-21
    • 2018-02-18
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    相关资源
    最近更新 更多