1. 程式人生 > 其它 >Spring迴圈依賴報錯Bean with name '**' has been injected into other beans [**] in its raw version as part

Spring迴圈依賴報錯Bean with name '**' has been injected into other beans [**] in its raw version as part

異常詳情

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.**

springboot迴圈依賴解決

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。

3.普通注入之間的迴圈依賴

比如:我現在有一個ServiceA需要呼叫ServiceB的方法,那麼ServiceA就依賴於ServiceB,那在ServiceB中再呼叫ServiceA的方法,就形成了迴圈依賴。Spring在初始化bean的時候就不知道先初始化哪個,bean就會報錯。

 

public class ClassA { 
@Autowired
ClassB classB; 
}