Spring 循环依赖
Spring Bean循环依赖
错误:
Error creating bean with name 'debtServiceImpl': Bean with name 'debtServiceImpl' has been injected into other beans [repayBillServiceImpl,investServiceImpl,receiveBillServiceImpl] in 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 'allowEagerInit' flag turned off, for example.
错误出现场景:A中依赖的有B,B中依赖的有A
public class ClassA { @Autowired ClassB classB; } public class ClassB { @Autowired ClassA classA ; }
解决:
一:重构
二:Bean配置
<bean id="ServiceDependent1" class="org.xyz.ServiceDependent1" lazy-init="true"> <constructor-arg ref="Service"/> </bean> <bean id="ServiceDependent2" class="org.xyz.ServiceDependent2" lazy-init="true"> <constructor-arg ref="Service"/> </bean>
三:加Lazy延迟加载注解
@Autowired @Lazy private ClassA classA; @Autowired @Lazy private ClassB classB;