Devin's Blogs

个人点滴记录

8.initApplicationEventMulticaster

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 初始化MessageSource。 如果在此上下文中未定义,则使用SimpleApplicationEventMulticaster。
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断beanFactory中是否有名字为applicationEventMulticaster的bean (即使beanFactory的祖先beanFactory包含也获取不到)
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
// 如果有,从beanFactory中获取
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 如果没有,新建 SimpleApplicationEventMulticaster 类作为 applicationEventMulticaster 的 Bean;
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}

9.onRefresh

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

钩子方法, 由子类实现

10.initApplicationEventMulticaster

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

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
protected void registerListeners() {
// Register statically specified listeners first.
// 遍历应用程序中存在的监听器集合,并将对应的监听器添加到监听器的多路广播器中
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 从 BeanFactory 中获取所有实现了 ApplicationListener 接口的 beanName,
// 并且添加到 applicationEventMulticaster 的 listenerBean 中
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}

// Publish early application events now that we finally have a multicaster...
// 有些事件可能要提前发出,将需要提前发出的事件发出并置空。同时将他们添加到 applicationEventMulticaster的multicastEvent中
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}

7.initMessageSource

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

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
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断beanFactory中是否有名字为messageSource的bean (即使beanFactory的祖先beanFactory包含也获取不到)
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 如果有,从beanFactory中获取
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
// 当父类 beanFactory 不为空,并且这个 bean 对象是 HierarchicalMessageSource 类型
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
// 类型强制转换,转换为 HierarchicalMessageSource 的类型
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
// 判断父类的 messageSource 是否为空,如果等于空,则设置父类的 messageSource
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
// 如果没有, 新建 DelegatingMessageSource 类作为 messageSource 的 bean
DelegatingMessageSource dms = new DelegatingMessageSource();
// 给这个DelegatingMessageSource添加父类消息源
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
// 将这个messageSource实例注册到Bean工厂中
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}

6. registerBeanPostProcessors

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

1
2
3
4
5
6
/**
* 实例化并注册所有BeanPostProcessor Bean,并遵守显式顺序(如果给定的话)。必须在应用程序Bean的任何实例化之前调用。
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

6.1 PostProcessorRegistrationDelegate#registerBeanPostProcessors

定位: org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory, AbstractApplicationContext)

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
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

// 找出所有实现了 BeanPostProcessor 接口的类的名称
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
// 预计 BeanPostProcessor实现类 目标个数
// 此处为什么要+1呢? 原因: 在此方法的最后会添加一个 BeanPostProcessorChecker 的类
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
// 添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 存放实现了 PriorityOrdered 接口的 BeanPostProcessor 集合
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 存放 Spring 内部实现了 BeanPostProcessor 的实例
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 存放实现了 Ordered 接口的 BeanPostProcessor 的 beanName 集合
List<String> orderedPostProcessorNames = new ArrayList<>();
// 存放普通(未实现排序接口)的 BeanPostProcessor 实例
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 如果 ppName 对应的 BeanPostProcessor 实例实现了 PriorityOrdered 接口,
// 则获取到 ppName 对应的 BeanPostProcessor 的实例添加到 priorityOrderedPostProcessors 中
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
// Spring内部实现了BeanPostProcessor的实例
internalPostProcessors.add(pp);
}
}
// 如果 ppName 对应的 BeanPostProcessor 实例没有实现 PriorityOrdered 接口,但是实现了 Ordered 接口,
// 那么则将 ppName 对应的 bean 实例添加到 orderedPostProcessorNames 中
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
// 将ppName添加到nonOrderedPostProcessorNames中
nonOrderedPostProcessorNames.add(ppName);
}
}

// First, register the BeanPostProcessors that implement PriorityOrdered.
// 1. 注册实现了 PriorityOrdered 接口的 BeanFactoryPostProcessors 实例对象
// 对实现了 PriorityOrdered 接口的 BeanPostProcessor 实例集合进行排序操作
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 注册实现了 PriorityOrdered 接口的 BeanPostProcessor 实例对象添加到 beanFactory 中
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

// Next, register the BeanPostProcessors that implement Ordered.
// 2. 注册实现 Ordered 的 BeanFactoryPostProcessors 实例对象
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
// 根据 ppName 找到对应的 BeanPostProcessor 实例对象
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 将实现了 Ordered 接口的 BeanPostProcessor 添加到 orderedPostProcessors 集合中
orderedPostProcessors.add(pp);
// 如果 ppName 对应的 BeanPostProcessor 实例也实现了 MergedBeanDefinitionPostProcessor 接口,
// 那么则将 ppName 对应的 bean 实例添加到 internalPostProcessors 中
if (pp instanceof MergedBeanDefinitionPostProcessor) {
// Spring内部实现了 BeanPostProcessor 的实例
internalPostProcessors.add(pp);
}
}
// 对实现了 Ordered 接口的 BeanPostProcessor 实例集合进行排序操作
sortPostProcessors(orderedPostProcessors, beanFactory);
// 注册实现了 Ordered 接口的 BeanPostProcessor 实例对象添加到 beanFactory 中
registerBeanPostProcessors(beanFactory, orderedPostProcessors);

// Now, register all regular BeanPostProcessors.
// 3. 注册普通(没有实现排序接口)的 BeanFactoryPostProcessors 实例对象
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
// 根据 ppName 获取对应的 BeanPostProcessor 实例对象
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 将普通的 BeanPostProcessor 添加到 nonOrderedPostProcessors 集合中
nonOrderedPostProcessors.add(pp);
// 如果 ppName 对应的 BeanPostProcessor 实例也实现了 MergedBeanDefinitionPostProcessor 接口,
// 那么则将 ppName 对应的 bean 实例添加到 internalPostProcessors 中
if (pp instanceof MergedBeanDefinitionPostProcessor) {
// Spring 内部实现了 BeanPostProcessor 的实例
internalPostProcessors.add(pp);
}
}
// 注册普通的 BeanPostProcessor 实例添加到 beanFactory 中
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // 注册

// Finally, re-register all internal BeanPostProcessors.
// 4. 注册所有 Spring 内部的 BeanPostProcessors 实例(实现了MergedBeanDefinitionPostProcessor接口)
sortPostProcessors(internalPostProcessors, beanFactory);
// Spring 内部的 BeanPostProcessors 实例(实现了 MergedBeanDefinitionPostProcessor 接口)
registerBeanPostProcessors(beanFactory, internalPostProcessors);

// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 最后,再置换一个新的ApplicationListenerDetector. ApplicationListenerDetector 已重写 equals 方法.
// 置换的原因是因为旧bean的属性singletonNames中已经存在有bdName了。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

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);
}

4. postProcessBeanFactory

按照标准修改应用上下文的内部 bean 工厂初始化。

所有 bean definition 都将被加载,但没有 bean 将被实例化。

这允许注册特殊的某些 ApplicationContext 实现中的 BeanPostProcessors 等。

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

1
2
3
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 钩子方法由子类实现
}

3. prepareBeanFactory

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

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
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 告知内部的bean工厂,使用上下文的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
// 设置 bean 表达式语言解析器
// 默认 StandardBeanExpressionResolver 成员变量 expressionParser 是 SpelExpressionParser (即 spring el表达式) 类型
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 添加 beanFactory 默认的 PropertyEditorRegistrar,主要是对 bean 的属性等设置管理的一个工具类
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

// Configure the bean factory with context callbacks.
// 添加 Bean 后置处理器
// 初始化bean之前处理 Aware 接口, EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware 和 ApplicationContextAware
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 设置要忽略自动装配的接口
// 为什么此处要对这些接口进行忽略,
// 原因:这些接口的实现是由容器通过set方法进行注入的,所以在使用 autowire 进行注入的时候需要将这些接口进行忽略
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 设置几个自动装配的特殊规则,当在进行ioc初始化的如果有多个实现,那么就使用指定的对象进行注入
// 在 Spring 自动装配的时候如果一个接口有多个实现类,使用 registerResolvableDependency 指定接口的实例
// 类似作用的有使用 @Primary
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

// Register early post-processor for detecting inner beans as ApplicationListeners.
// 添加 Bean 后置处理器
// 初始化 bean 之后处理事件监听器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 增加对 AspectJ 的支持,在 java 中织入分为三种方式,分为编译器织入,类加载器织入,运行期织入,编译器织入是指在java编译器,采用特殊的编译器,将切面织入到java类中,
// 而类加载期织入则指通过特殊的类加载器,在类字节码加载到JVM时,织入切面,运行期织入则是采用 cglib 和 jdk 进行切面的织入
// Aspectj 提供了两种织入方式,第一种是通过特殊编译器,在编译器,将 Aspectj 语言编写的切面类织入到 java 类中,第二种是类加载期织入,就是下面的l oad time weaving
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}

// Register default environment beans.
// 注册默认的系统环境 bean 到一级缓存中
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
// 环境变量
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
// 系统属性
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
// 系统环境变量
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}

ResourceEditorRegistrar

2.1.1 解析 xml 文件

DefaultBeanDefinitionDocumentReader#parseDefaultElement

解析默认标签

定位: org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseDefaultElement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 默认标签的解析
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
// 解析 import 标签
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
// 解析 alias 标签
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
// 解析 bean 标签
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// 解析 beans 标签 (递归调用)
doRegisterBeanDefinitions(ele);
}
}

DefaultBeanDefinitionDocumentReader#processBeanDefinition

定位: org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
// beanDefinitionHolder 是 beanDefinition 对象的封装类,封装了BeanDefinition, bean的名字和别名, 用它来完成向IOC容器的注册
// new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray)
// 得到 beanDefinitionHolder 就意味着 beanDefinition 是通过 BeanDefinitionParserDelegate 对 xml 元素的信息按照 spring 的 bean 规则进行解析得到的
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
// 向ioc容器注册解析得到的 beanDefinition
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
// 在 beanDefinition 向 ioc 容器注册完成之后发送消息
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}

BeanDefinitionParserDelegate#parseBeanDefinitionElement

解析 bean 基本属性 (id, name, aliases)

定位: org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionElement(Element, BeanDefinition)

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
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
// 解析id属性
String id = ele.getAttribute(ID_ATTRIBUTE);
// 解析name属性
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
// 如果bean有别名,则将别名分割解析
List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}

String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isTraceEnabled()) {
logger.trace("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}

if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
// 如果在解析bean定义期间发生问题, 则返回null
// 对bean元素的详细解析
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
// 如果不存在 beanName,那么根据 spring 中提供的命名规则为当前 beanDefinition 生成对应的 beanName
// beanName = (([parentName + $child]) | ([factoryBeanName + $created])) + beanClassName + # + ObjectUtils.getIdentityHexString(definition)
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
// 生成 Spring 内部的 beanName 和 aliases
// beanName = beanClassName + # + index(索引 0, 1, 2, 3 ...)
// eg: beanName = com.devinx3.service.impl.UserServiceImpl#0
// eg: aliases = com.devinx3.service.impl.UserServiceImpl
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isTraceEnabled()) {
logger.trace("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}

return null;
}
BeanDefinitionParserDelegate#parseBeanDefinitionElement

解析 bean 的其他属性

定位: org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionElement(Element, String, BeanDefinition)

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
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {

this.parseState.push(new BeanEntry(beanName));
// 解析class属性
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
// 解析parent属性
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}

try {
// 创建装在bean信息的AbstractBeanDefinition对象,实际上创建了 GenericBeanDefinition 对象
AbstractBeanDefinition bd = createBeanDefinition(className, parent);

// 解析bean标签的各种其他属性
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
// 设置 description 信息
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));

// 解析元数据
parseMetaElements(ele, bd);
// 解析 lookup-method 属性
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
// 解析 replaced-method 属性
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

// 解析构造函数参数
parseConstructorArgElements(ele, bd);
// 解析 property 子元素
parsePropertyElements(ele, bd);
// 解析 qualifier 子元素
parseQualifierElements(ele, bd);

bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));

return bd;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}

return null;
}
BeanDefinitionParserDelegate#parseBeanDefinitionAttributes

定位: org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionAttributes

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
// 解析bean标签的各种其他属性
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {

// 解析 singleton 属性, 在 1.x 后废弃
if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
error("Old 1.x 'singleton' attribute in use - upgrade to 'scope' declaration", ele);
}
// 解析 scope 属性
else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {
bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
}
else if (containingBean != null) {
// Take default from containing bean in case of an inner bean definition.
// 如果是内部BeanDefinition,则从 containingBean 中获取 scope 的值。
bd.setScope(containingBean.getScope());
}
// 解析 abstract 属性
if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {
bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
}
// 解析 lazy-init 属性
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
if (isDefaultValue(lazyInit)) {
lazyInit = this.defaults.getLazyInit();
}
// 如果没有设置或者设置成其他字符都会被设置为false
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));

// 解析 autowire 属性
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));

// 解析 depends-on 属性
if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS));
}

// 解析 autowire-candidate 属性
String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
if (isDefaultValue(autowireCandidate)) {
String candidatePattern = this.defaults.getAutowireCandidates();
if (candidatePattern != null) {
String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {
bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
}

// 解析 primary 属性
if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
}

// 解析 init-method 属性
if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE);
bd.setInitMethodName(initMethodName);
}
else if (this.defaults.getInitMethod() != null) {
bd.setInitMethodName(this.defaults.getInitMethod());
bd.setEnforceInitMethod(false);
}

// 解析 destroy-method 属性
if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE);
bd.setDestroyMethodName(destroyMethodName);
}
else if (this.defaults.getDestroyMethod() != null) {
bd.setDestroyMethodName(this.defaults.getDestroyMethod());
bd.setEnforceDestroyMethod(false);
}

// 解析 factory-method 属性
if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
}

// 解析 factory-bean 属性
if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
}

return bd;
}
BeanDefinitionParserDelegate#parseMetaElements

定位: org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseMetaElements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 解析元数据
public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
// 获取当前节点的所有子节点
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, META_ELEMENT)) {
// meta 节点
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
// 使用 key/value 构造 beanMetadataAttribute
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
// 记录信息
attributeAccessor.addMetadataAttribute(attribute);
}
}
}

DefaultBeanDefinitionDocumentReader#parseDefaultElement

解析自定义标签

定位: org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseCustomElement(Element, BeanDefinition)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
// 获取标签对应的命名空间
String namespaceUri = getNamespaceURI(ele);
if (namespaceUri == null) {
return null;
}
// XmlBeanDefinitionReader#registerBeanDefinitions 创建的 namespaceHandlerResolver
// 根据命名空间找到对应的 NamespaceHandler (对应关系文件 spring.schemas)
// 通过继承 NamespaceHandlerSupport 来定制 NamespaceHandler
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
// 调用定制的 NamespaceHandler 进行解析
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}

NamespaceHandler#parse

定位: org.springframework.beans.factory.xml.NamespaceHandlerSupport#parse

1
2
3
4
5
6
public BeanDefinition parse(Element element, ParserContext parserContext) {
// 获取自定义组件名 对应的解析方法
BeanDefinitionParser parser = findParserForElement(element, parserContext);
// 调用ComponentScanBeanDefinitionParser实现类中的 parse方法
return (parser != null ? parser.parse(element, parserContext) : null);
}

NamespaceHandlerSupport#findParserForElement

定位: org.springframework.beans.factory.xml.NamespaceHandlerSupport#findParserForElement

1
2
3
4
5
6
7
8
9
10
11
12
// 从map中根据组件名称获取绑定的解析方法
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
// 获取组件名称
String localName = parserContext.getDelegate().getLocalName(element);
// this.parsers 成员变量定义: Map<String, BeanDefinitionParser> parsers = new HashMap<>();
BeanDefinitionParser parser = this.parsers.get(localName);
if (parser == null) {
parserContext.getReaderContext().fatal(
"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
}
return parser;
}

2.1 loadBeanDefinitions

AbstractRefreshableApplicationContext#loadBeanDefinitions

定位: org.springframework.context.support.AbstractRefreshableApplicationContext#loadBeanDefinitions

加载配置文件(执行 xml, groovy 和注解方式)并生成 BeanDefinitions

AbstractXmlApplicationContext#loadBeanDefinitions

定位: org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 加载 xml 配置文件, 并注册 beanDefinition
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 创建一个 XmlBeanDefinitionReader, 并通过回调设置到 beanFactory 中
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

// Configure the bean definition reader with this context's
// resource loading environment.
// 给 beanDefinitionReader 对象设置对象
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
// 设置要用于解析的 SAX 实体解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
// 初始化 beanDefinitionReader 对象,此处设置配置文件是否要进行验证
initBeanDefinitionReader(beanDefinitionReader);
// 加载并注册 beanDefinition
loadBeanDefinitions(beanDefinitionReader);
}

定位: org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(XmlBeanDefinitionReader)

1
2
3
4
5
6
7
8
9
10
11
12
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
// 从指定的资源加载 BeanDefinition
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
// 从指定的资源位置加载 BeanDefinition
reader.loadBeanDefinitions(configLocations);
}
}

XmlBeanDefinitionReader#loadBeanDefinitions

定位org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions(EncodedResource)

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
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Loading XML bean definitions from " + encodedResource);
}

// 获取已经加载的资源记录
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
// 从 encodedResource 中获取已经封装的 Resource 对象, 并再次从 Resource 中获取其中的 inputStream
try {
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 实际从指定的XML文件加载 BeanDefinition (核心处理步骤)
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}

XmlBeanDefinitionReader#doLoadBeanDefinitions

定位: org.springframework.beans.factory.xml.XmlBeanDefinitionReader#doLoadBeanDefinitions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
/*
* 此解析过程是由 XmlBeanDefinitionReader 来完成,
* 从 重载 loadBeanDefinitions方法 (String[] -> string -> Resource[] -> resource) ,
* 最终开始将 resource 读取成一个 document 文档,根据文档的节点信息封装成一个个的 BeanDefinition 对象
*/
try {
// 将inpustream转换成Document, 此处获取 xml 文件的 document 对象,
Document doc = doLoadDocument(inputSource, resource);
// 注册 xml 文件定义的 BeanDefinition
int count = registerBeanDefinitions(doc, resource);
// ... 省略日志打印
return count;
}
catch (...) {
// ... 省略
}
}
XmlBeanDefinitionReader#registerBeanDefinitions

定位: org.springframework.beans.factory.xml.XmlBeanDefinitionReader#registerBeanDefinitions

1
2
3
4
5
6
7
8
9
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
// 委托模式,BeanDefinitionDocumentReader 委托这个类进行 document 的解析
// 创建 BeanDefinitionDocumentReader, 以用于实际从XML文档读取bean定义
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
// 从给定的DOM文档中读取bean定义,并将他们向注册到注册表中
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
XmlBeanDefinitionReader#doRegisterBeanDefinitions

定位: org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions

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
// 创建BeanDefinitionParserDelegate委托对象,交给parseBeanDefinitions处理
protected void doRegisterBeanDefinitions(Element root) {
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);

if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
// We cannot use Profiles.of(...) since profile expressions are not supported
// in XML config. See SPR-12458 for details.
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
// 解析 xml 的前置逻辑(扩展点, 钩子方法)
preProcessXml(root);
// 真正的解析方法, 处理默认命名空间的标签("import"、"alias"、"bean") 和 自定义的标签
parseBeanDefinitions(root, this.delegate);
// 解析 xml 的后置处理逻辑(扩展点, 钩子方法)
postProcessXml(root);

this.delegate = parent;
}
DefaultBeanDefinitionDocumentReader#parseBeanDefinitions

定位: org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseBeanDefinitions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
// 文件的命名空间为 http://www.springframework.org/schema/beans
// 解析 "import", "alias", "bean", "beans" 标签
parseDefaultElement(ele, delegate);
}
else {
// 处理自定义的标签
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}

2. AbstractApplicationContext#obtainFreshBeanFactory

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

1
2
3
4
5
6
7
8
9
/**
* 告诉子类刷新内部 bean 工厂
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 初始化 BeanFactory, 并进行XML文件读取,并将获取的 BeanFactory 记录在当前实体的属性中
refreshBeanFactory();
// 返回当前实体的 beanFactory 属性
return getBeanFactory();
}

AbstractRefreshableApplicationContext#refreshBeanFactory

定位: org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory

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
/**
* 此实现执行此上下文的底层bean工厂的实际刷新,关闭前一个bean工厂(如果有的话),并为上下文生命周期的下一个阶段初始化一个新的bean工厂。
* @throws BeansException
*/
@Override
protected final void refreshBeanFactory() throws BeansException {
// 判断是否存在 BeanFactory, 存在则销毁所有Beans,并且关闭BeanFactory
// 目的是避免重复加载BeanFactory
if (hasBeanFactory()) {
// 如果实例化了BeanFactory,则先销毁所有的单例Bean
destroyBeans();
// 关闭BeanFactory,也就是将beanFactory的值置为null
closeBeanFactory();
}
try {
// 创建具体的 beanFactory,这里创建的是 DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 为了序列化指定id,可以从id反序列化到beanFactory对象
beanFactory.setSerializationId(getId());
// 定制beanFactory,设置相关属性,包括是否允许覆盖同名称的不同定义的对象以及循环依赖
// 有默认实现, 钩子方法
customizeBeanFactory(beanFactory);
// 加载配置文件(执行 xml, groovy 和注解方式)并生成 BeanDefinitions
// 初始化 XmlBeanDefinitionReader, 并进行XML文件读取及解析, 默认命名空间的解析, 自定义标签的解析
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}

AbstractRefreshableApplicationContext#createBeanFactory

定位: org.springframework.context.support.AbstractRefreshableApplicationContext#createBeanFactory

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
// 创建一个默认 内部bean 工厂
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
public DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
super(parentBeanFactory);
}
}
public AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
this();
setParentBeanFactory(parentBeanFactory);
}
public AbstractAutowireCapableBeanFactory() {
super();
// 依赖项检查和自动装配时忽略的依赖项接口
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
}

AbstractRefreshableApplicationContext#customizeBeanFactory

定位: org.springframework.context.support.AbstractRefreshableApplicationContext#customizeBeanFactory

用于给子类提供一个自由配置的机会,默认实现:

1
2
3
4
5
6
7
8
9
10
11
12
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
// 如果属性allowBeanDefinitionOverriding不为空,设置给beanFactory对象相应属性,是否允许覆盖同名称的不同定义的对象
// 默认false,不允许覆盖
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// 如果属性allowCircularReferences不为空,设置给beanFactory对象相应属性,是否允许bean之间存在循环依赖
// 默认false,不允许循环引用
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}

1. prepareRefresh

定位: org.springframework.context.support.AbstractApplicationContext#prepareRefresh
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
// 准备刷新,设置应用开启的时间还有active标志,并且执行一些属性源的初始化工作
protected void prepareRefresh() {
// Switch to active.
// 设置容器启动实现
this.startupDate = System.currentTimeMillis();
// 设置容器的关闭标志位
this.closed.set(false);
// 设置容器的开启标志位
this.active.set(true);

if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}

// Initialize any placeholder property sources in the context environment.
// 初始化placeholder属性, 默认未实现, 由子类实现
initPropertySources();

// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 创建并获取环境对象,验证需要的属性文件是否都已经放入环境中
getEnvironment().validateRequiredProperties();

// Store pre-refresh ApplicationListeners...
// 判断刷新前的应用程序监听器集合是否为空,如果为空,则将监听器添加到此集合中
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
// 如果不等于空,则清空集合元素对象
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}

// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 允许应用启动之前的事件,当多播器一旦可用的时候,可用立刻响应发布的事件。
this.earlyApplicationEvents = new LinkedHashSet<>();
}
0%