spring 自动装配 aop 循环依赖 [英] spring autowired aop circular dependency

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

问题描述

我使用带有 @ComponentScan 的 java 配置来初始化我的 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)class).

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 &乙;

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),然后它检测到自动连接到 B 和 A 的 C 与 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 的任何依赖,请确保尽可能声明它们 @Lazy,以便让它们也通过其他后处理器.

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:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html

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

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