我正在使用Java配置和@ComponentScan
来初始化我的bean,以及@EnableAspectJAutoProxy(proxyTargetClass=true)
使用cglib代理。
在这个项目中,我们有很多通过@Autowired
相互关联的生成服务。它们运行得非常好。
但是,对于其中一些服务,我添加了@Async
(我还在我的@Configuration
类上添加了@EnableAsync(proxyTargetClass = true)
)。
之后,我遇到了以下问题:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'ConversationUserLocalService': Bean with name 'ConversationUserLocalService' has been injected into other beans [ConversationUserHistoryLocalService] i
n its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'a
llowEagerInit' flag turned off, for example.
我猜这是因为Spring在AOP创建代理之前使用@Async
方法注入了服务,这可能是问题所在。问题应该如何解决?
为了尝试澄清我的问题,假设我有:
@Service A、B和C;
A已经自动装配了B和C,B已经自动装配了A和C,C已经自动装配了A和B;
C有一个标记为@Async的方法。
当Spring初始化applicationContext时,它尝试初始化A,但需要B和C,因此它会初始化它们。 但最终,AOP试图对C进行代理(因为@Async),然后它检测到自动装配到B和A中的C与C的代理不同,因此失败了。
我希望这可以更好地解释正在发生的事情。