Bean创建三级缓存
# Bean创建三级缓存
通过三级缓存解决循环依赖问题. 使用到的地方主要是 DefaultSingletonBeanRegistry
# 关键源码部分
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
// 1级缓存, 用于存放已属性赋值,初始化后的 单例bean
private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
// 3级缓存 存储创建BEAN的工厂
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16);
// 2级缓存 用于存放已经实例化,还未做代理属性赋值的操作 单例
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap(16);
// 已经注册到单例池的bean name
private final Set<String> registeredSingletons = new LinkedHashSet(256);
// 通过 beanName 寻找单例
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从一级缓存中拿
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 锁住一级缓存
synchronized(this.singletonObjects) {
// 1级
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 2级
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
// 3级
ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 创建一个bean的实例
singletonObject = singletonFactory.getObject();
// 将其放入二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
// 从三级缓存中移除
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
上次更新: 2023/06/12, 10:31:06