【问题标题】:Spring Boot application context broken when adding AOP advices添加 AOP 建议时 Spring Boot 应用程序上下文中断
【发布时间】:2017-03-13 15:31:57
【问题描述】:

我正在尝试使用 this question 中的代码作为我自己的 AOP 日志记录的基础。但是,当我添加建议时,应用程序上下文不再加载。

@Aspect
@Component
public class MyLogger {

    /** Handle to the log file */
    private final Log log = LogFactory.getLog(getClass());

    public MyLogger () {}

    @AfterReturning("execution(* org.my.package.*.*(..))")
    public void logMethodAccessAfter(JoinPoint joinPoint) {
        log.info("***** Completed: " + joinPoint.getSignature().getName() + " *****");
        System.out.println("***** Completed: " + joinPoint.getSignature().getName() + " *****");
    }

    @Before("execution(* org.my.package.*.*(..))")
    public void logMethodAccessBefore(JoinPoint joinPoint) {
        log.info("***** Starting: " + joinPoint.getSignature().getName() + " *****");
        System.out.println("***** Starting: " + joinPoint.getSignature().getName() + " *****");
    }
}

异常堆栈,一大堆Could not autowire field

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxxxxx.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)

UserService 是一个完全不相关的类,如果我注释掉带有@AfterReturning@Before 注释的方法,一切都会重新运行。

存在AOP依赖:

[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:1.3.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-aop:jar:1.3.0.RELEASE:compile

知道为什么会这样吗?我什至不知道从哪里开始寻找。

【问题讨论】:

  • UserService 是否实现了接口?
  • @fateddy 不,它没有...所以我需要为与建议匹配的包中的所有 bean 创建接口,在本例中为org.my.package,对吗?
  • 不——你不需要为你的 bean 创建接口。问题可能与 spring 如何创建 AOP 代理有关:JDK-Dynamic Proxies(默认)与 CGLIB 代理。通过将 @EnableAspectJAutoProxy(proxyTargetClass=true) 添加到您的配置类之一来启用 CGLIB 代理。另请参阅此处的答案:stackoverflow.com/a/35579802/4516887

标签: java spring spring-boot aop spring-aop


【解决方案1】:

您的 bean UserService 现在是代理,与注入所需的类型不匹配。 可能的解决方法:

  • 创建接口UserService和实现该接口的服务类
  • 启用基于 CGLIB 的代理 (@EnableAspectJAutoProxy(proxyTargetClass=true))
  • 在编译时编织方面。

【讨论】:

  • 它也对我有用,感谢@JEY 的提问和回答,请您参考一些关于 Spring 代理和使用 spring 的 aop 架构的好的文档
  • @fateddy ,请告诉我关于spring proxy和aop的好文档
猜你喜欢
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 2020-04-26
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
相关资源
最近更新 更多