深度解析 Spring 源码:三级缓存机制探究
在Spring框架中,Bean定义的注册过程通常是在容器启动时进行的,这个过程涉及到Bean的加载、注册以及可能的依赖解析。为了提高性能,Spring采用了缓存机制,即三级缓存。
- 单例缓存(Singleton Cache):用于存储已经创建的单例Bean。
- 原型缓存(Prototype Cache):用于存储已经创建的原型Bean的共享原型实例。
- 缓存的工厂(Cache of Factory Beans):用于存储已经创建的工厂Bean实例。
以下是Spring源码中的部分关键函数,展示了三级缓存的使用方式:
public class DefaultSingletonBeanRegistry {
// 缓存创建好的单例Bean
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
// 缓存正在创建的单例Bean的工厂
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>();
// 标记单例Bean是否在创建中
private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
// 获取单例Bean,如果未创建,则标记为正在创建,创建后添加到缓存
public Object getSingleton(String beanName) {
// ...
synchronized (this.singletonObjects) {
// 检查是否已经创建
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && !this.singletonsCurrentlyInDestruction.contains(beanName)) {
// 标记为正在创建
beforeSingletonCreation(beanName);
try {
// 真正的创建逻辑
singletonObject = singletonFactory.getObject();
// 将创建好的Bean添加到缓存
addSingleton(beanName, singletonObject);
}
// ...
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
// 添加单例Bean到缓存
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonsCurrentlyInCreation.remove(beanName);
// 可能的依赖解析和初始化操作
// ...
}
}
// 其他方法略...
}
在这个例子中,getSingleton
方法展示了如何从三级缓存中获取单例Bean。如果缓存中不存在,它会标记该Bean为“正在创建”,并且在Bean创建后将其添加到缓存中。这样,后续的请求就可以直接从缓存中获取Bean,从而提高了容器的启动速度和运行效率。
评论已关闭