【发布时间】: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