code-20230420115040

获取 Bean 的 getSingleton()方法代码

protected Object getSingleton(String beanName, boolean allowEarlyReference) {  
    //首先从一级缓存singletonObjects中获取  
    Object singletonObject = this.singletonObjects.get(beanName);  
    //如果获取不到,就从二级缓存earlySingletonObjects中获取   
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {  
        synchronized (this.singletonObjects) {  
            singletonObject = this.earlySingletonObjects.get(beanName);  
            //如果还是获取不到,就从三级缓存singletonFactory中获取  
            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;  
}