Springboot循环依赖解决办法

最近在使用Spingboot做项目的时候,在引入shiro后,启动项目一直报错

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.

后来在网上找了半天说是依赖循环,检查了一下代码,确实存在循环依赖的现象,但是项目快要上线,再去改代码逻辑是来不及了,于是各种找解决方案,终于算是找到了。

首先说一下什么是依赖循环,比如:我现在有一个ServiceA需要调用ServiceB的方法,那么ServiceA就依赖于ServiceB,那在ServiceB中再调用ServiceA的方法,就形成了循环依赖。Spring在初始化bean的时候就不知道先初始化哪个bean就会报错。

public class ClassA {
    @Autowired
    ClassB classB;
}

public class ClassB {
    @Autowired
    ClassA classA ;
}
那如何解决循环依赖,当然最好的方法是重构你的代码,进行解耦,但是重构不是一时的事情,那就使用下面的方法:

第一种:

<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>

在你的配置文件中,在互相依赖的两个bean的任意一个加上lazy-init属性。

第二种:

@Autowired
    @Lazy
    private ClassA classA;
    @Autowired
    @Lazy
    private ClassB classB;
在你注入bean时,在互相依赖的两个bean上加上@Lazy注解也可以。

以上两种方法都能延迟互相依赖的其中一个bean的加载,从而解决循环依赖的问题。

经验分享 程序员 微信小程序 职场和发展