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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM