Java 如何解决Spring IoC中bean之间的循环依赖?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25997512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve circular dependency between beans in Spring IoC?
提问by Alex
Suppose I have a bean which depends on another bean, and another bean depends on first bean.
假设我有一个依赖于另一个 bean 的 bean,另一个 bean 依赖于第一个 bean。
Bean#1 -> Bean#2 -> Bean#1
How can I resolve this issue?
我该如何解决这个问题?
采纳答案by Abhiroop Sarkar
This is from Spring Reference
这是来自Spring 参考
You can generally trust Spring to do the right thing. It detects configuration problems, such as references to non-existent beans and circular dependencies, at container load-time. Spring sets properties and resolves dependencies as late as possible, when the bean is actually created.
您通常可以相信 Spring 会做正确的事情。它在容器加载时检测配置问题,例如对不存在的 bean 的引用和循环依赖。Spring 在真正创建 bean 时尽可能晚地设置属性并解析依赖项。
So it instantiates both beans and injects them onto each other.
所以它实例化了两个 bean 并将它们注入到彼此中。
EDIT
编辑
In your case BeanCurrentlyInCreationException
mostly arose due to constructor injection. If that is the case mostly using setter injection instead of constructor injection will solve the issue. Constructor injection typically gives rise to the chicken-egg problem!
在您的情况下,BeanCurrentlyInCreationException
主要是由于构造函数注入引起的。如果是这种情况,主要使用 setter 注入而不是构造函数注入将解决问题。构造函数注入通常会引发鸡-蛋问题!
回答by matsev
You can get around by using setter injection. However, generally this is a bad idea since the code will be harder to maintain and test. I suggest that you refactor your code to only have unidirectional dependencies, e.g.
你可以通过使用 setter 注入来解决。然而,通常这是一个坏主意,因为代码将更难维护和测试。我建议你重构你的代码只具有单向依赖,例如
BeanA -> BeanB
Another way of solving this is to pull out the common behavior in a third bean class, and then let the two initial classes depend on it, e.g.
解决这个问题的另一种方法是在第三个bean类中拉出共同的行为,然后让两个初始类依赖它,例如
BeanA -> BeanC
BeanB -> BeanC