单例 bean 的加载是首先要从单例缓存中获取,如果缓存中没有才会进行bean 的加载。这里我们分析从缓存获取bean的过程。
在 AbstractBeanFactory
当中的doGetBean()
方法中首先从单例bean缓存中获取bean
Object sharedInstance = getSingleton(beanName);
继续跟踪源码到了 DefaultSingletonBeanRegistry
中的 getSingleton()
方法,如下:
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从单例缓存中获取bean
Object singletonObject = this.singletonObjects.get(beanName);
// 单例缓存中没有该bean且 当前bean 正在创建
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
// 加锁
synchronized (this.singletonObjects) {
// 从早期单例bean缓存中获取bean
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果bean为空且允许早期创建
if (singletonObject == null && allowEarlyReference) {
// 获取该bean的beanFactory
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 使用 singletonFactory 创建bean
singletonObject = singletonFactory.getObject();
// 添加到 earlySingletonObjects 缓存中
this.earlySingletonObjects.put(beanName, singletonObject); // 添加到 singletonFactories 缓存中
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
- 从
singletonObjects
获取 - 如果
singletonObjects
没有则从earlySingletonObjects
中获取 - 如果
earlySingletonObjects
中没有,则使用bean的 beanFactory 也就是从singletonFactories
获取singletonFactory
,使用singletonFactory
获取到singletonObject
- 将 singletonObject 添加到
earlySingletonObjects
缓存中,从singletonFactories
移除bea对应的beanFactory - return singletonObject