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的加载,从而解决循环依赖的问题。





本文参考以下文章:

http://stackoverflow.com/questions/11348794/spring-circular-reference-example点击打开链接

http://forum.spring.io/forum/spring-projects/container/23983-allowrawinjectiondespitewrapping-flag点击打开链接


  • 12
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值