org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '*******Controller': Unsatisfied dependency expressed through field '*******Service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '*******Service': Unsatisfied dependency expressed through field '######Service'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name '######*****Service': Bean with name '######*****Service' has been injected into other beans [######*****!!!!Service] 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.
依赖循环是什么:
我现在有一个ServiceA需要调用ServiceB的方法,那么ServiceA就依赖于ServiceB,那在ServiceB中再调用ServiceA的方法,就形成了循环依赖。Spring在初始化bean的时候就不知道先初始化哪个bean就会报错。
例如
public class ServiceA {
@Autowired
ServiceB serviceB;
}
public class ServiceB {
@Autowired
ServiceA serviceA ;
}
那如何解决循环依赖,当然最好的方法是重构你的代码,进行解耦,但是重构不是一时的事情,那就使用下面的方法:
第一种:
<bean id="Service1" class="*******1" lazy-init="true">
<constructor-arg ref="Service"/>
</bean>
<bean id="Service2" class="********2" lazy-init="true">
<constructor-arg ref="Service"/>
</bean>
在你的配置文件中,在互相依赖的两个bean的任意一个加上lazy-init属性。
第二种:
@Autowired
@Lazy
private ClassA classA;
@Autowired
@Lazy
private ClassB classB;
在你注入bean时,在互相依赖的两个bean上加上@Lazy注解也可以。
以上两种方法都能延迟互相依赖的其中一个bean的加载,从而解决循环依赖的问题。