Spring 源码之核心加载方法(5) 执行 BeanFactoryPostProcessor

5. invokeBeanFactoryPostProcessors

定位: org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 实例化并调用所有注册的BeanFactoryPostProcessor Bean,并遵循显式顺序(如果给定的话)。 一定在单例实例化之前被调用。
* @param beanFactory
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 1. 拿到当前应用上下文 beanFactoryPostProcessors 变量中的值
// 2. 实例化并调用所有已注册的BeanFactoryPostProcessor
/*
* 默认情况下,通过 getBeanFactoryPostProcessors() 来获取已经注册的 BeanFactoryPostProcessor,
* 但是默认是空的, 可以 AbstractApplicationContext#postProcessBeanFactory 方法中添加
*/
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
/*
* 检测LoadTimeWeaver并准备编织(如果在此期间发现)
* 例如 通过ConfigurationClassPostProcessor注册的@Bean方法
*/
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}

5.1 PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

定位: org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory, List)

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 无论是什么情况,优先执行 BeanDefinitionRegistryPostProcessors
// 将已经执行过的 BeanFactoryPostProcessor 存储在 processedBeans 中,防止重复执行
Set<String> processedBeans = new HashSet<>();

// Spring 默认创建的是 DefaultListableBeanFactory, 且实现了BeanDefinitionRegistry接口,所以为true
if (beanFactory instanceof BeanDefinitionRegistry) { // beanFactory是BeanDefinitionRegistry实例
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
/*
* 两个接口是不同的, BeanDefinitionRegistryPostProcessor 是BeanFactoryPostProcessor 的子集
* BeanFactoryPostProcessor 主要针对的操作对象是 BeanFactory,
* 而 BeanDefinitionRegistryPostProcessor 主要针对的操作对象是 BeanDefinition
*/
// 用于存放普通的 BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 用于存放 BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

// 遍历所有的 beanFactoryPostProcessors, 将 BeanDefinitionRegistryPostProcessor 和普通 BeanFactoryPostProcessor 区分开
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 如果是 BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 直接执行 BeanDefinitionRegistryPostProcessor 接口的 postProcessBeanDefinitionRegistry 方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 添加到 registryProcessors,用于后续执行postProcessBeanFactory方法
registryProcessors.add(registryProcessor);
}
else {
// 如果只是普通的BeanFactoryPostProcessor,添加到regularPostProcessors,
// 用于后续执行postProcessBeanFactory方法
regularPostProcessors.add(postProcessor);
}
}

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// 用于保存本次要执行的 BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 找出所有实现 PriorityOrdered 的 BeanDefinitionRegistryPostProcessor 接口的 Bean 的 beanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 检测是否实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 获取名字对应的 bean 实例,添加到 currentRegistryProcessors 中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 将要被执行的 BeanFactoryPostProcessor 名称添加到 processedBeans,避免后续重复执行
processedBeans.add(ppName);
}
}
// 按照优先级进行排序操作
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加到 registryProcessors 中,用于最后执行 postProcessBeanFactory 方法
registryProcessors.addAll(currentRegistryProcessors);
// 遍历 currentRegistryProcessors,执行 postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 执行完毕之后,清空 currentRegistryProcessors
currentRegistryProcessors.clear();

// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 找出所有实现 Ordered 的 BeanDefinitionRegistryPostProcessor 接口的 Bean 的 beanName
// 此处需要重复查找的原因在于上面的执行过程中可能会新增其他的 BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 检测是否实现了 Ordered 接口,并且还未执行过
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 获取名字对应的 bean 实例,添加到 currentRegistryProcessors中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 将要被执行的 BeanFactoryPostProcessor 名称添加到 processedBeans,避免后续重复执行
processedBeans.add(ppName);
}
}
// 按照优先级进行排序操作
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加到 registryProcessors 中,用于最后执行 postProcessBeanFactory 方法
registryProcessors.addAll(currentRegistryProcessors);
// 遍历 currentRegistryProcessors,执行 postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 执行完毕之后,清空 currentRegistryProcessors
currentRegistryProcessors.clear();

// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 调用所有剩下的BeanDefinitionRegistryPostProcessors
boolean reiterate = true;
while (reiterate) {
reiterate = false;
// 找出所有实现 BeanDefinitionRegistryPostProcessor 接口的类
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) { // 跳过已经执行过的
// 获取名字对应的 bean 实例,添加到 currentRegistryProcessors中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 将要被执行的 BeanFactoryPostProcessor 名称添加到 processedBeans,避免后续重复执行
processedBeans.add(ppName);
reiterate = true;
}
}
// 按照优先级进行排序操作
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加到 registryProcessors 中,用于最后执行 postProcessBeanFactory 方法
registryProcessors.addAll(currentRegistryProcessors);
// 遍历 currentRegistryProcessors,执行 postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 执行完毕之后,清空 currentRegistryProcessors
currentRegistryProcessors.clear();
}

// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 调用所有 BeanDefinitionRegistryPostProcessor#postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 最后,调用入参 beanFactoryPostProcessors 中的普通 BeanFactoryPostProcessor#postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}

else {
// Invoke factory processors registered with the context instance.
// 如果 beanFactory 不归属于 BeanDefinitionRegistry 类型,那么直接执行 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}

// 到这里为止,入参 beanFactoryPostProcessors 和容器中的所有 BeanDefinitionRegistryPostProcessor 已经全部处理完毕.
// 下面开始处理容器中所有的 BeanFactoryPostProcessor
// 可能会包含一些实现类,只实现了 BeanFactoryPostProcessor,并没有实现 BeanDefinitionRegistryPostProcessor 接口

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 不要在这里初始化 FactoryBeans:我们需要保留所有未初始化的常规bean,以使bean工厂后处理器对其应用!
// 找到所有实现 BeanFactoryPostProcessor 接口的类
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 用于存放实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 用于存放实现了 Ordered 接口的 BeanFactoryPostProcessor 的 beanName
List<String> orderedPostProcessorNames = new ArrayList<>();
// 用于存放普通 BeanFactoryPostProcessor 的 beanName
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 遍历 postProcessorNames, 将 BeanFactoryPostProcessor 按实现PriorityOrdered接口、实现Ordered接口、普通三种区分开
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
// 跳过已经执行过的 BeanFactoryPostProcessor
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 添加实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor 到priorityOrderedPostProcessors
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 添加实现了 Ordered 接口的 BeanFactoryPostProcessor 的 beanName 到 orderedPostProcessorNames
orderedPostProcessorNames.add(ppName);
}
else {
// 添加剩下的普通 BeanFactoryPostProcessor 的 beanName 到 nonOrderedPostProcessorNames
nonOrderedPostProcessorNames.add(ppName);
}
}

// 1. 调用实现了 PriorityOrdered 的 BeanFactoryPostProcessors
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 对实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor 进行排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 遍历实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor,执行 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 2. 调用实现了 Ordered 的 BeanFactoryPostProcessors
// 创建存放实现了 Ordered 接口的 BeanFactoryPostProcessor 集合
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
// 遍历存放实现了 Ordered 接口的 BeanFactoryPostProcessor 名字的集合
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); // 获取实例对象
}
// 对实现了 Ordered 接口的 BeanFactoryPostProcessor 进行排序操作
sortPostProcessors(orderedPostProcessors, beanFactory);
// 遍历实现了 Ordered 接口的 BeanFactoryPostProcessor,执行 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// Finally, invoke all other BeanFactoryPostProcessors.
// 3. 调用普通 BeanFactoryPostProcessors
// 创建存放普通的BeanFactoryPostProcessor的集合
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
// 遍历存放实现了普通 BeanFactoryPostProcessor 名字的集合
for (String postProcessorName : nonOrderedPostProcessorNames) {
// 将普通的 BeanFactoryPostProcessor 添加到集合中
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); // 获取实例对象
}
// 遍历普通的 BeanFactoryPostProcessor,执行 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // 调用

// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 清除元数据缓存(mergeBeanDefinitions、allBeanNamesByType、singletonBeanNameByType)
// 因为后处理器可能已经修改了原始元数据,例如 替换值中的占位符...
beanFactory.clearMetadataCache();
}

5.2 BeanFactoryPostProcessor 常用接口和实现类

BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry 可以动态增删改查 BeanDefinition

ConfigurationClassPostProcessor

ConfigurationClassPostProcessor 实现 BeanDefinitionRegistryPostProcessor 接口

img

定位: ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 定位、加载、解析、注册相关注解
*
* Derive further bean definitions from the configuration classes in the registry.
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
// 根据对应的 registry 对象生成 hashcode 值,此对象只会操作一次,如果之前处理过则抛出异常
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
// 将马上要进行处理的 registry 对象的 id 值放到已经处理的集合对象中
this.registriesPostProcessed.add(registryId);

// 处理配置类的 bean 定义信息
processConfigBeanDefinitions(registry);
}

5.2.1 ConfigurationClassPostProcessor#postProcessBeanFactory

定位: ConfigurationClassPostProcessor#postProcessBeanFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 添加 CGLIB 增强处理及 ImportAwareBeanPostProcessor 后置处理类
*
* Prepare the Configuration classes for servicing bean requests at runtime
* by replacing them with CGLIB-enhanced subclasses.
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + beanFactory);
}
this.factoriesPostProcessed.add(factoryId);
if (!this.registriesPostProcessed.contains(factoryId)) {
// BeanDefinitionRegistryPostProcessor hook apparently not supported...
// Simply call processConfigurationClasses lazily at this point then.
// BeanDefinitionRegistryPostProcessor 埋点不支持, 此时调用 processConfigurationClasses 处理配置类的 bean 定义信息
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
}
// 对添加 @Configuration注解的类, 生成cglib代理
enhanceConfigurationClasses(beanFactory);
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}
5.2.1.2 ConfigurationClassPostProcessor.processConfigBeanDefinitions

定位: ConfigurationClassPostProcessor#processConfigBeanDefinitions

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/**
* 构建和验证一个类是否被 @Configuration 修饰,并做相关的解析工作
*
* Build and validate a configuration model based on the registry of
* {@link Configuration} classes.
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
// 创建存放 BeanDefinitionHolder 的对象集合
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
// 当前 registry 就是 DefaultListableBeanFactory,获取所有已经注册的 BeanDefinition 的 beanName
String[] candidateNames = registry.getBeanDefinitionNames();

// 遍历所有要处理的 beanDefinition 的名称, 筛选对应的 beanDefinition(被注解修饰的)
for (String beanName : candidateNames) {
// 获取指定名称的 BeanDefinition 对象
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
// 如果 beanDefinition 中的 configurationClass 属性不等于空,那么意味着已经处理过,输出日志信息
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
// 判断当前 BeanDefinition 是否是一个配置类,并为 BeanDefinition 设置属性为 lite 或者 full,此处设置属性值是为了后续进行调用
// 如果 Configuration 配置 proxyBeanMethods 代理为 true 则为 full
// 如果加了 @Bean、@Component、@ComponentScan、@Import、@ImportResource 注解,则设置为 lite
// 如果配置类上被 @Order 注解标注,则设置 BeanDefinition 的 order 属性值
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
// 添加到对应的集合对象中
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}

// Return immediately if no @Configuration classes were found
// 如果没有发现任何配置类,则直接返回
if (configCandidates.isEmpty()) {
return;
}

// Sort by previously determined @Order value, if applicable
// 如果适用,则按照先前确定的 @Order 的值排序
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});

// Detect any custom bean name generation strategy supplied through the enclosing application context
// 判断当前类型是否是 SingletonBeanRegistry 类型
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
// 类型的强制转换
sbr = (SingletonBeanRegistry) registry;
// 判断是否有自定义的 beanName 生成器
if (!this.localBeanNameGeneratorSet) {
// 获取自定义的 beanName 生成器
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
// 如果有自定义的命名生成策略
if (generator != null) {
//设置组件扫描的 beanName 生成策略
this.componentScanBeanNameGenerator = generator;
// 设置 import bean name 生成策略
this.importBeanNameGenerator = generator;
}
}
}

// 如果环境对象等于空,那么就重新创建新的环境对象
if (this.environment == null) {
this.environment = new StandardEnvironment();
}

// Parse each @Configuration class
// 实例化 ConfigurationClassParser 类,并初始化相关的参数,完成配置类的解析工作
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);

// 创建两个集合对象
// 存放相关的 BeanDefinitionHolder 对象
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
// 存放扫描包下的所有 bean
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
// 解析带有 @Controller、@Import、@ImportResource、@ComponentScan、@ComponentScans、@Bean 的 BeanDefinition
parser.parse(candidates);
// 将解析完的 Configuration配置类进行校验,
// 1、配置类不能是 final;
// 2、@Bean 修饰的方法必须可以重写以支持 CGLIB
parser.validate();

// 获取所有的 bean,包括扫描的 bean 对象,@Import 导入的 bean 对象
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
// 清除掉已经解析处理过的配置类
configClasses.removeAll(alreadyParsed);

// Read the model and create bean definitions based on its content
// 判断读取器是否为空,如果为空的话,就创建完全填充好的 ConfigurationClass 实例的读取器
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 核心方法,将完全填充好的 ConfigurationClass 实例转化为 BeanDefinition 注册入 IOC 容器
this.reader.loadBeanDefinitions(configClasses);
// 添加到已经处理的集合中
alreadyParsed.addAll(configClasses);

candidates.clear();
// 这里判断 registry.getBeanDefinitionCount() > candidateNames.length 的目的是为了知道 reader.loadBeanDefinitions(configClasses) 这一步有没有向 BeanDefinitionMap 中添加新的 BeanDefinition
// 实际上就是看配置类(例如 AppConfig 类会向 BeanDefinitionMap 中添加 bean)
// 如果有,registry.getBeanDefinitionCount() 就会大于 candidateNames.length
// 这样就需要再次遍历新加入的 BeanDefinition,并判断这些 bean 是否已经被解析过了,如果未解析,需要重新进行解析
// 这里的 AppConfig 类向容器中添加的 bean,实际上在 parser.parse() 这一步已经全部被解析了
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
// 如果有未解析的类,则将其添加到 candidates 中,这样 candidates 不为空,就会进入到下一次的 while 的循环中
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());

// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}

if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
5.2.1.1 ConfigurationClassParser#parse

定位: ConfigurationClassParser#parse (Set)

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
public void parse(Set<BeanDefinitionHolder> configCandidates) {
// 循环遍历 configCandidates
for (BeanDefinitionHolder holder : configCandidates) {
// 获取 BeanDefinition
BeanDefinition bd = holder.getBeanDefinition();
// 根据 BeanDefinition 类型的不同,调用 parse 不同的重载方法,实际上最终都是调用 processConfigurationClass() 方法
try {
// 注解类型
if (bd instanceof AnnotatedBeanDefinition) {
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
// 有 class 对象的
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}

// 执行找到的 DeferredImportSelector
// DeferredImportSelector 是 ImportSelector 的一个子类
// ImportSelector 被设计成和 @Import 注解同样的效果,但是实现了 ImportSelector 的类可以条件性的决定导入某些配置
// DeferredImportSelector 的设计都是在所有其他的配置类被处理后才进行处理
this.deferredImportSelectorHandler.process();
}

定位: ConfigurationClassParser#processConfigurationClass

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
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}

// 第一次进入的时候,configurationClass 的 size 为 0,existingClass 肯定为 null,在此处处理 configuration 重复 import
// 如果同一个配置类被处理两次,两次都属于被 import 的则合并导入类,返回,如果配置类不是被导入的,则移除旧的使用新的配置类
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
// 如果要处理的配置类 configClass 在已经分析处理的配置类记录中已存在,合并两者的 importBy 属性
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}

// Recursively process the configuration class and its superclass hierarchy.

// 处理配置类,由于配置类可能存在父类(若父类的全类名是以java开头的,则除外),所有需要将 configClass 变成 sourceClass 去解析,然后返回 sourceClass 的父类。
// 如果此时父类为空,则不会进行 while 循环去解析,如果父类不为空,则会循环的去解析父类
// SourceClass 的意义:简单的包装类,目的是为了以统一的方式去处理带有注解的类,不管这些类是如何加载的
// 如果无法理解,可以把它当做一个黑盒,不会影响阅读 spring 源码的主流程
SourceClass sourceClass = asSourceClass(configClass);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);

// 将解析的配置类存储起来,这样回到 parse 方法时,能取到值
this.configurationClasses.put(configClass, configClass);
}

定位: ConfigurationClassParser#doProcessConfigurationClass

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {

// @Configuration 继承了 @Component
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass);
}

// Process any @PropertySource annotations
// 如果配置类上加了 @PropertySource 注解,那么就解析加载 properties 文件,并将属性添加到 spring 上下文中
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}

// Process any @ComponentScan annotations
// 处理 @ComponentScan 或者 @ComponentScans 注解,并将扫描包下的所有 bean 转换成填充后的 ConfigurationClass
// 此处就是将自定义的 bean 加载到 IOC 容器,因为扫描到的类可能也添加了 @ComponentScan 和 @ComponentScans 注解,因此需要进行递归解析
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
// 解析 @ComponentScan 和 @ComponentScans 配置的扫描的包所包含的类
// 比如 basePackages = org.devin, 那么在这一步会扫描出这个包及子包下的 class,然后将其解析成 BeanDefinition
// (BeanDefinition 可以理解为等价于 BeanDefinitionHolder)
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
// 通过上一步扫描包 org.devin,有可能扫描出来的bean中可能也添加了 ComponentScan 或者 ComponentScans 注解.
//所以这里需要循环遍历一次,进行递归(parse),继续解析,直到解析出的类上没有 ComponentScan 和 ComponentScans
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
// 判断是否是一个配置类,并设置 full 或 lite 属性
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
// 通过递归方法进行解析
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}

// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), true);

// Process any @ImportResource annotations
// 处理 @ImportResource 注解,导入 spring 的配置文件
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}

// Process individual @Bean methods
// 处理加了 @Bean 注解的方法,将 @Bean 方法转化为 BeanMethod 对象,保存再集合中
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}

// Process default methods on interfaces
// 处理接口的默认方法实现,从 jdk8 开始,接口中的方法可以有自己的默认实现,因此如果这个接口的方法加了 @Bean 注解,也需要被解析
processInterfaces(configClass, sourceClass);

// Process superclass, if any
// 解析父类,如果被解析的配置类继承了某个类,那么配置类的父类也会被进行解析
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}

// No superclass -> processing is complete
return null;
}

定位: ConfigurationClassParser#processImports

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, boolean checkForCircularImports) {

// 如果使用 @Import 注解修饰的类集合为空,那么直接返回
if (importCandidates.isEmpty()) {
return;
}

if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
// 添加到栈中,用于处理循环引入的问题
this.importStack.push(configClass);
try {
// 遍历每一个 @Import 注解的类
for (SourceClass candidate : importCandidates) {
// 检验配置类 Import 引入的类是否是 ImportSelector 子类
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
// 候选类是一个导入选择器->委托来确定是否进行导入
Class<?> candidateClass = candidate.loadClass();
// 通过反射生成一个 ImportSelect 对象
ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
this.environment, this.resourceLoader, this.registry);
// 判断引用选择器是否是 DeferredImportSelector 接口的实例
// 如果是则应用选择器将会在所有的配置类都加载完毕后加载
if (selector instanceof DeferredImportSelector) {
// 将选择器添加到 deferredImportSelectorHandler 实例中,预留到所有的配置类加载完成后统一处理自动化配置类
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
}
else {
// 获取引入的类,然后使用递归方式将这些类中同样添加了 @Import 注解引用的类
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
processImports(configClass, currentSourceClass, importSourceClasses, false);
}
}
// 如果是实现了 ImportBeanDefinitionRegistrar 接口的 bd
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
// 候选类是 ImportBeanDefinitionRegistrar -> 委托给当前注册器注册其他 bean
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
this.environment, this.resourceLoader, this.registry);
/*
* 放到当前 configClass 的 importBeanDefinitionRegistrars 中
* 在 ConfigurationClassPostProcessor 处理 configClass 时会随之一起处理
*/
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
// 候选类既不是 ImportSelector 也不是 ImportBeanDefinitionRegistrar -->将其作为 @Configuration 配置类处理
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass));
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}

5.2.2 ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry

定位: ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 定位、加载、解析、注册相关注解
*
* Derive further bean definitions from the configuration classes in the registry.
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
// 根据对应的 registry 对象生成 hashcode 值,此对象只会操作一次,如果之前处理过则抛出异常
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
// 将马上要进行处理的 registry 对象的 id 值放到已经处理的集合对象中
this.registriesPostProcessed.add(registryId);

// 处理配置类的 bean 定义信息
processConfigBeanDefinitions(registry);
}