spring自动连线aop循环依赖项

spring自动连线aop循环依赖项,spring,aop,spring-aspects,Spring,Aop,Spring Aspects,我将java配置与@ComponentScan一起使用,以初始化我的bean 和@enableSpectJautoproxy(proxyTargetClass=true)使用cglib代理 在这个项目中,我们使用@autowired在它们之间自动连接了许多生成的服务。它工作得很好 但是,对于其中一些服务,我添加了@Async(我还在@Configuration类中添加了@EnableAsync(proxyTargetClass=true)) 在那之后,我得到: Caused by: org.sp

我将java配置与
@ComponentScan
一起使用,以初始化我的bean 和
@enableSpectJautoproxy(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
方法注入服务。 这可能是问题所在吗? 我该怎么修

为了澄清我的问题,假设我有:

@服务A、B和C

A有自动接线的B&C,B有自动接线的A&C,C有自动接线的A&B

C有一个标记为@Async的方法

当Spring初始化applicationContext时,它尝试初始化A,但需要B&C,所以它会初始化它们。但毕竟,AOP试图创建一个C的代理(因为@Async),然后它检测到自动连接到B中的C和a与C的代理不同,所以失败了


我希望这能解释更多发生的事情。

最后,我在服务上使用了
@Lazy
(带有
@Async
注释的方法),,它们是自动连接的。
通过这种方式,我猜Spring只在需要时初始化并自动连接这些服务,而不是在应用程序上下文初始化时进行初始化。

我通过将@Qualifier与@Autowire一起添加,成功地解决了类似的问题,例如:

@Autowired
@Qualifier("publisher")
private Publisher publisher;

AsyncConfigurer配置类在应用程序上下文引导的早期得到初始化。如果您需要任何对其他bean的依赖,请确保尽可能将它们声明为“懒惰”,以便让它们也通过其他后处理器


参考JavaDoc:

我有同样的问题,我解决了这个问题:

  • 我确定哪个
    @Autowired
    属性是循环依赖的原因

    例如:

    (识别的提示只需尝试注释并找出哪个属性是破坏应用程序的原因)

  • 一旦识别,只需在该
    @Autowired
    变量上使用
    @Lazy

    例如:

    应用程序运行顺利


  • 请发布a嘿,你能解释一下吗:“它检测到自动连接到B中的C和a与C的代理不同”当Spring创建一个代理将异步行为添加到C中时,它不会更新a和B上的引用。所以它们都引用了C的原始版本。感谢你的解释。还有一件事,这取决于spring初始化服务的顺序。在您的示例中,如果spring首先初始化了C,那么同样的异常也会发生?因此
    @Lazy
    @Autowired
    将服务插入到其他服务中得到了想要的结果。
    @Autowired
    private TestService testService;
    
    @Lazy
    @Autowired
    private TestService testService;