/**
* 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
*/
@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;
}
spring 源码中的3个缓存map
/** Cache of singleton objects: bean name to bean instance. */
/** singletonObjects 一级缓存,可以理解为spring单利池 存放完整的bean*/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
/** 这个二级缓存 是一个bean工厂,可以生产bean(循环依赖aop--通过cglib代理产生一个新的类,问题等可以在这里实现),
如果二级缓存直接是一个bean 的话,很多需要对bean 的加工都不能实现,这里对aop的实现是通过一个后置处理器AnnotationAwareAspectJAutoProxyCreator */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
/** 三级缓存spring 为什么要三级缓存呢,
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
从二级缓存singletonFactories remove,然后放入三级,因为有多个相同的依赖注入的话,
防止singletonFactories 的重复创建,可以直接在earlySingletonObjects 中获取,提高性能。就好比你每次看病找老中医看了一个药方子,
以后有这个病了就看药方子就行了,不用再重复去医院排队缴费,找老中医说你的症状,直接拿着药方子去买药吃就行了 */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);