48

我正在使用 java config@ComponentScan来初始化我的 bean 并@EnableAspectJAutoProxy(proxyTargetClass=true)使用 cglib 代理。

在这个项目中,我们有很多生成的服务在它们之间使用@Autowired. 它工作得很好。

但是,对于我添加的其中一些服务@Async(我也添加@EnableAsync(proxyTargetClass = true)到我的@Configuration课程中)。

之后,我得到:

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@Async在 AOP 创建代理之前使用方法注入服务。这可能是问题吗?我应该如何修复它?

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

@服务 A、B 和 C;

A 自动接线 B 和 C,B 自动接线 A 和 C,C 自动接线 A 和 B;

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

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

我希望这可以解释更多正在发生的事情。

4

4 回答 4

48

最后,我使用@Lazyon 服务(使用用 注释的方法@Async以及它们被自动装配的位置对其进行了整理。这样,我猜 Spring 只会在需要时初始化和自动装配这些服务,而不是在应用程序上下文初始化时。

于 2015-03-11T18:28:21.537 回答
13

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

  1. 我确定了哪个@Autowired属性是循环依赖的原因。

    例如:

    @Autowired
    private TestService testService;
    

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

  2. 一旦确定,只需在此变量@Lazy之上使用。@Autowired

    例如:

    @Lazy
    @Autowired
    private TestService testService;
    

    并且应用程序运行顺利。

于 2020-04-16T13:49:37.010 回答
11

AsyncConfigurer配置类在应用程序上下文引导的早期初始化。如果您需要那里的其他 bean 的任何依赖关系,请确保尽可能声明它们@Lazy,以便让它们也通过其他后处理器。

参考JavaDoc:https ://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html

于 2019-05-21T08:40:08.980 回答
-3

我设法通过添加@Qualifier 和@Autowire 来解决类似的问题,例如:

@Autowired
@Qualifier("publisher")
private Publisher publisher;
于 2017-03-16T15:47:20.847 回答