springboot启动报错Bean with name ‘xxxxService‘ has been injected into other beans

今天在本地测试启动项目的时候报错:

Bean with name ‘commonService’ has been injected into other beans [] 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就会报错。

  1. 循环依赖是什么?
    Bean A 依赖 B,Bean B 依赖 A这种情况下出现循环依赖。
    Bean A → Bean B → Bean A
    更复杂的间接依赖造成的循环依赖如下。
    Bean A → Bean B → Bean C → Bean D → Bean E → Bean A

  2. 循环依赖会产生什么结果?
    当Spring正在加载所有Bean时,Spring尝试以能正常创建Bean的顺序去创建Bean。
    例如,有如下依赖:
    Bean A → Bean B → Bean C
    Spring先创建beanC,接着创建bean B(将C注入B中),最后创建bean A(将B注入A中)。

但当存在循环依赖时,Spring将无法决定先创建哪个bean。这种情况下,Spring将产生异常BeanCurrentlyInCreationException。

解决办法:
1、重构代码,进行解耦
2、在注入bean时,在互相依赖的两个bean上加上@Lazy注解

@Autowired     
@Lazy      
private ClassA classA; 
 
@Autowired 
@Lazy      
private ClassB classB; 

文章转载于:https://www.ycblog.top/article?articleId=135&commentPageNum=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值