1. 程式人生 > 其它 >springboot啟動報錯Bean with name ‘xxxxService‘ has been injected into other beans

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