Spring Autowired AOP循环依赖 [英] spring autowired aop circular dependency

查看:707
本文介绍了Spring Autowired AOP循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Java config与@ComponentScan一起使用以初始化我的bean 和@EnableAspectJAutoProxy(proxyTargetClass=true)使用cglib代理.

I'm using java config with @ComponentScanin order to initialize my beans and @EnableAspectJAutoProxy(proxyTargetClass=true)to use cglib proxies.

在此项目中,我们使用@Autowired在它们之间自动连接了许多生成的服务.效果很好.

In this project we have a lots of generated services autowired between them using @Autowired. It works pretty well.

但是,对于其中的某些服务,我添加了@Async(在我的@Configuration类中也添加了@EnableAsync(proxyTargetClass = true)).

But, for some of these services I've added @Async (I've also added @EnableAsync(proxyTargetClass = true)on my @Configurationclass).

在那之后,我得到:

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方法注入服务. 这可能是问题吗? 我应该如何解决?

I guess this is because Spring is injecting the service with @Asyncmethod BEFORE AOP creates the proxy. Could this be the problem? How I should fix it?

为了阐明我的问题,假设我有:

In order to try to clarify my problem, let's say I have:

@服务A,B& C;

@Service A, B & C;

A已自动连接B& C,B已自动连线A& C,C已自动连线A& B;

A has autowired B & C, B has autowired A & C, C has autowired A & B;

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

C has a method marked as @Async.

Spring初始化applicationContext时,它将尝试初始化A,但需要B& C,因此将其初始化.但是毕竟,AOP尝试创建C的代理(因为@Async),然后它检测到将C自动连接到B中,而A与C的代理不同,因此失败.

When Spring initialize applicationContext, it tries to initialize A, but needs B & C, so it initializes them. But after all, AOP tries to make a proxy of C (because @Async) and then it detects that autowired C into B and A is not the same as proxy of C so it fails.

我希望这可以解释更多情况.

I hope this can explain a little more what is happening.

推荐答案

AsyncConfigurer 配置类在应用程序上下文引导中提前初始化.如果您在那里需要对其他bean的任何依赖,请确保尽可能将它们声明为惰性",以使它们也可以通过其他后处理器.

AsyncConfigurer configuration classes get initialized early in the application context bootstrap. If you need any dependencies on other beans there, make sure to declare them 'lazy' as far as possible in order to let them go through other post-processors as well.

参考JavaDoc:

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

这篇关于Spring Autowired AOP循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆