Spring 解决循环依赖
程序员文章站
2022-07-10 10:47:32
...
在编写Spring 时,会遇到循环依赖的问题,如下:
<bean id="cycleA" class="di.cycledependency.CycleDependencyA"> <constructor-arg ref="cycleB"/> </bean> <bean id="cycleB" class="di.cycledependency.CycleDependencyB"> <constructor-arg ref="cycleA"/> </bean>
public class CycleDependencyA { private final CycleDependencyB b; public CycleDependencyA(CycleDependencyB b) { this.b = b; } } public class CycleDependencyB { private final CycleDependencyA a; public CycleDependencyB(CycleDependencyA a) { this.a = a; } }
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'cycleA': Requested bean is currently in creation: Is there an unresolvable circular reference? at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:339) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:215) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:367) ... 29 more
解决方法是用Setter代替构造函数:
package di.cycledependency; public class CycleDependencyA { private CycleDependencyB b; public void setB(CycleDependencyB b) { this.b = b; } } package di.cycledependency; public class CycleDependencyB { private CycleDependencyA a; public void setA(CycleDependencyA a) { this.a = a; } }
<bean id="cycleA" class="di.cycledependency.CycleDependencyA"> <property name="b" ref="cycleB"/> </bean> <bean id="cycleB" class="di.cycledependency.CycleDependencyB"> <property name="a" ref="cycleA"/> </bean>
推荐阅读