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

相关文章
相关标签/搜索