一、Spring三级缓存的作用?
解决对象之间的依赖问题
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
//1级缓存 用于存放 已经属性赋值 初始化后的 单列BEAN
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
//2级缓存 用于存在已经实例化,还未做代理属性赋值操作的 单例
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
//3级缓存 存储单例BEAN的工厂
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
//已经注册的单例池里的beanName
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
//正在创建中的beanName
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
//缓存查找bean 如果1级没有,从2级获取,也没有,从3级创建放入2级
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName); //1级
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName); //2级
if (singletonObject == null && allowEarlyReference) {
//3级缓存 在doCreateBean中创建了bean的实例后,封装ObjectFactory放入缓存的
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//创建未赋值的bean
singletonObject = singletonFactory.getObject();
//放入到二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
//从三级缓存删除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
}