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就会报错。

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

循环依赖会产生什么结果?
当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注解

 

 


————————————————
版权声明:本文为CSDN博主「ycblog.top」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41916305/article/details/118569174

posted @ 2022-01-10 13:16  LZ太热  阅读(1705)  评论(0编辑  收藏  举报