Spring获取单例bean方法的思考

本文深入探讨了Spring如何通过DefaultSingletonBeanRegistry获取单例bean,特别是涉及循环依赖的解决策略。分析了三级缓存(singletonObjects、singletonFactories、earlySingletonObjects)在处理循环依赖中的作用,并解释了为什么需要早期单例对象集合。文章还讨论了@Autowired注解在构造函数和setter方法中解决循环依赖的方式。
摘要由CSDN通过智能技术生成

Spring获取单例bean方法的思考

使用的SpringMVC版本是5.1.8.RELEASE

下面是DefaultSingletonBeanRegistry类中通过类名获取单例的源码


/** 单例对象的缓存:从bean名称到bean实例 */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

/** 单例对象的缓存:从bean名称到objects实例工厂 */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

/** 早期单例对象的缓存:从bean名称到bean实例 */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

/**
 * 返回以给定名称注册的(原始)singleton对象
 * <p> 检查已经实例化了singleton,还允许对当前创建的singleton进行早期引用(解析循环引用)
 * @param beanName 要查找的bean的名称
 * @param allowEarlyReference 是否应创建早期引用
 * @return 已注册的singleton对象,或者如果未找到任何对象返回null
 */
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
   
	Object singletonObject = this.singletonObjects.get(beanName);
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
   
		synchronized (this.singletonObjects) {
   
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
   
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
   
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}

/**
 * 返回一个指定的bean实例,可以是共享的,也可以是依赖的
 * @param name 要检索的bean的名称
 * @
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值