Spring對加載的bean之間循環依賴的處理

根據下面文檔的敘述,簡言之:

  1. 對於相互之間經過構造函數注入相互循環依賴的狀況,Spring會拋出BeanCurrentlyInCreationException錯誤。
  2. 若是AB兩個beans是經過屬性注入的循環依賴(Singleton),spring會經過先對其中一個bean賦值以後再對另一個bean賦值,來打破循環依賴。所以不會有問題。其實是用默認構造函數初始化A以後,放入earlyBeanFactory,使之能夠被獲取,而後實現循環依賴的處理。
    3.對於prototype的bean,spring沒法處理循環依賴,由於spring不緩存prototype的bean

Circular dependenciesspring

If you use predominantly constructor injection, it is possible to create an unresolvable circular dependency scenario.緩存

For example: Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection. If you configure beans for classes A and B to be injected into each other, the Spring IoC container detects this circular reference at runtime, and throws a >BeanCurrentlyInCreationException.dom

One possible solution is to edit the source code of some classes to be configured by setters rather than constructors. Alternatively, avoid constructor injection and use setter injection only. In other words, although it is not recommended, you can configure circular dependencies with setter injection.函數

Unlike the typical case (with no circular dependencies), a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken/egg scenario).ui

相關文章
相關標籤/搜索