Spring_循环依赖

@Component
class A{
	@Resource
	private B b;
}

@Component
class B{
	@Resource
	private A a;
}

Spring在创建单例bean时是如何解决循环依赖?
注:在多例模式下,会抛出BeanCurrentlyInCreationException(beanName);

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {

	/** Cache of singleton objects: bean name to bean instance. */
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/** Cache of singleton factories: bean name to ObjectFactory. */
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	/** Cache of early singleton objects: bean name to bean instance. */
	private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
	
	/** Set of registered singletons, containing the bean names in registration order. */
	private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

	/** Names of beans that are currently in creation. */
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

创建过程:

  • getSingleton(),A
  • doCreateBean(),提前暴露,earlySingletonExplore=true;调用addSingletonFactories()将A工厂添加到singletonFactories
  • populateBean():给A属性赋值,发现B
  • getSingleton(),B
  • doCreateBean(),提前暴露,earlySingletonExplore=true;调用addSingletonFactories()将B工厂添加到singletonFactories
  • populateBean():给B属性赋值,发现A
  • getSingleton(),A,此时根据集合singletonsCurrentlyInCreation 发现A已经在创建过程中,则从A工厂产出一个 early-A添加到earlySingletonObjects ,并且将singletonFactories中A工厂移除
  • 通过addSingleton()将earlySingletonObjects中的 early-A填充到B中
  • 将B添加到singletonObjects 中,此时A也完成创建,将A也添加到singletonObjects
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值