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的名称
* @