getSingleton()
DefaultSingletonBeanRegistry
类中184行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) {
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 != NULL_OBJECT ? singletonObject : null);
}
getSingleton()
方法作用是去查找单例的bean有没有注入到spring容器中,分为三个判断步骤
- 首先判断
singletonObjects
中有没有对应的bean,singletonObjects
存储的是已经创建好的单例bean。 - 如果第一步没找到,那么去
earlySingletonObjects
中查找,earlySingletonObjects
存储的是经过实例化的bean对象,还没有进行属性赋值和初始化。 - 如果第二步还是没有找到,那么去
singletonFactories
中进行查找,singletonFactories
存储的是经过实例化并且被AOP包装后的代理类,意在解决循环依赖时AOP时产生的问题
If there is AOP, a depends on B, and B depends on A. After instantiation, a exposes it, starts injecting attributes, finds references to B, B starts instantiation, uses the object exposed by a, encapsulates it into a proxy object after initialization, and a injects B after the proxy and acts as a proxy. Then B in agent a is B after the proxy, but a in B after the proxy is a useless proxy.