添加AOP建议时,Spring Boot应用程序上下文中断

时间:2016-03-17 16:14:26

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

我试图使用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

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

1 个答案:

答案 0 :(得分:2)

您的bean UserService现在是一个代理,并且不符合所需的注入类型。 可能的解决方法:

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