在 Spring IOC(2) 我们介绍了Spring IOC中的prepareRefreshobtainFreshBeanFactoryprepareBeanFactory

本章介绍AbstractApplicationContext#refresh的第4、5、6个方法

  • postProcessBeanFactory(beanFactory)

  • invokeBeanFactoryPostProcessors

  • registerBeanPostProcessors

postProcessBeanFactory

AbstractApplicationContext中的postProcessBeanFactory方法为空方法。

postProcessBeanFactory这个方法跟BeanFactoryPostProcessor接口中的方法一样,但是它的功能是提供给子类进行添加一些额外的功能,比如添加BeanPostProcessor接口的实现,或者定制一些其他的功能,因为这个方法你可以拿到BeanFactory,自然是可以对它进行一些功能的定制的。

1
2
3
4
5
@FunctionalInterface
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

这里看下Spring 提供的子类GenericWebApplicationContext是如何实现的:

1
2
3
4
5
6
7
8
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
if (this.servletContext != null) {
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
}
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext);
}

这里注册了一个ServletContextAwreProcessorbeanFactory中,ServletContexAwareProcessor是一个BeanPostProcessor接口的子类。

重点BeanFactoryPostProcessor

接下来分析AbstractApplicationContext#refresh中的第5个方法invokeBeanFactoryPostProcessors方法,这个方法用来注册和执行BeanFactoryPostProcessor的。

invokeBeanFactoryPostProcessors方法

1
2
3
4
5
6
7
8
9
10
11
12
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 执行所有的BeanFactoryPostProcessor 这里是重点
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)
// aop的处理
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}

这个方法的重点在invokeBeanFactoryPostProcessors,获取BeanFactoryPostProcessor的集合,这里获取到都是用户在定制BeanFactoryadd加入进去的

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
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 放置已经处理的Bean
Set<String> processedBeans = new HashSet<>();

// 先进性外部BFPP的处理,并且判断当前Factory是否是BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 保存BFPP的Bean
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 保存BDRPP的Bean
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

// 开始处理外部传入的BFPP
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 先处理BDRPP
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 直接调用BDRPP的接口方法,后面的postProcessBeanFactory 方法统一处理
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 加入到BDRPP的集合中
registryProcessors.add(registryProcessor);
}
else {
// 加入到BDRPP的集合中
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.
// 不要在这里初始化FactoryBeans:我们需要保留所有常规bean
// 未初始化,让bean工厂后处理器应用于它们!
// 在实现PriorityOrdered、Ordered和其余的BeanDefinitionRegistryPostProcessors之间分离
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 首先,调用实现PriorityOrdered的BeanDefinitionRegistryPostProcessors。按类型获取BeanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 判断当前的beanName是否实现了PriorityOrdered
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 加入到当前注册的BDRPP集合中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 加入到已经处理的bean集合中
processedBeans.add(ppName);
}
}
// 对当前的BDRPP进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 将当前的BDRPP全部加入到最前面定义的BDRPP的集合中
registryProcessors.addAll(currentRegistryProcessors);
// 执行当前的BDRPP的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空当前的BDRPP
currentRegistryProcessors.clear();

// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 再次获取BDRPP,因为上面的执行可能还会加入新的BDRPP进来
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 判断是否已经处理过,并且是否实现了Ordered接口
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}

// 再次进行排序、将当前的BDRPP全部加入到最前面定义的BDRPP的集合中、执行当前的BDRPP的postProcessBeanDefinitionRegistry方法
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();

// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 最后,调用所有其他BeanDefinitionRegistryPostProcessors,直到不再出现。
// 循环去获取BDRPP,然后进行排序、执行操作,直到所有的BDRPP全部执行完
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}

// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 执行bdrpp、bfpp 中的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}

else {
// Invoke factory processors registered with the context instance.
// 如果不是,那么直接执行bfpp的postProcessBeanFactory
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 获取BFPP的beanName集合
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 定义实现了PriorityOrdered的BFPP
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 如果已经处理过了就不做处理
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}

// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}

这个方法的主要流程如下:

  1. 先执行外部传入的BeanFactoryPostProcessor的实现

  2. 处理时先处理BeanFactoryPostProcessor的子接口BeanDefinitionRegistryPostProcessor的实现

  3. 处理BeanDefinitionRegistryPostProcessor实现的时候先处理实现了PriorityOrdered接口的实现

  4. 处理完PriorityOrdered接口实现的类之后再处理实现了Ordered接口的实现

  5. 处理完Ordered接口的实现类之后处理没有排序的

  6. 处理完BeanDefinitionRegistryPostProcessor的实现之后处理BeanFactoryPostProcessor的实现

  7. 处理顺序也是PriorityOrededOrdered,没有排序的

img

通过流程图可以简化为:先遍历执行外部传入的BFPP,再执行BDRPP,再执行BFPP三部分,处理每一部分可能会进行排序操作,排序按照PriorityOrderedOrderednoSort进行排序再执行。

这其中有1个接口比较关键BeanDefinitionRegistryPostProcessor,它是BeanFactoryPostProcessor 的一个子类,它里面包含一个方法叫postProcessBeanDefinitionRegistry,这个方法非常重要,在实现类ConfigurationClassPostProcessor中就是使用这个方法进行注解的解析的,而且这个类也是实现SpringBoot自动装配的关键。

ConfigurationClassPostProcessor这个类是什么时候加入到Spring容器的呢?

在我们启动容器的时候,Spring会进行BeanDefinition的扫描,如果我们在开启了注解扫描,那么这注解扫描的类中个时候就会自动添加多个BeanDefinitionSpring容器中,beanNameorg.springframework.context.annotation.internalConfigurationAnnotationProcessor

其他还有几个:

1
2
3
4
5
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor

ConfigurationClassPostProcessor

ConfigurationClassPostProcessor同时实现了BeanDefinitionRegisterPostProcessor方法的postProcessBeanDefinitionRegistryBeanFactoryPostProcessorpostProcessBeanFactory方法,在解析时先执行postProcessBeanDefinitionRegistry,再执行postProcessBeanFactory

先看postProcessBeanDefinitionRegistry做了什么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
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);
}
this.registriesPostProcessed.add(registryId);
// 处理配置的BeanDefinition
processConfigBeanDefinitions(registry);
}

这个方法的核心是processConfigBeanDefinitions流程如下:

  1. 先进行合格的beanDefinition的检查
    1. 获取到注解的元数据信息
    2. 判断是包含@Configuration注解,包含则合格,否则判断是否包含了@Component@ComponentScan@Import@ImportResource注解,包含则合格,如果都不包含则不合格
  2. 对合格的BeanDefinition排序
  3. 创建一个解析@Configuration注解的解析器
  4. 对合格的BeanDefinition集合进行解析

总的来说就是解析了这些注解:@Component@PropertySource@PropertySources@ComponentScan@ComponentScans@Import@ImportResource@Bean,然后将标有这些注解的解析成BeanDefinition,如果加上了@Conditionnal注解,那么按照条件进行解析

img

registerBeanPostProcessors

接下来讲解refresh方法的第6个方法registerBeanPostProcessors ,对BeanPostProcessor的注册。

1
2
3
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

这个方法还是在PostProcessorRegistrationDelegate类中

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
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 通过类型获取beanNames
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的数量
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
// 注册BeanPostProcessorChecker
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// PriorityOrdered的BPP
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 内部的BPP
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 匹配是否是PriorityOrdered类型的BPP,是就加入进去
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
// 判断是否是合并的mbdpp,
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}

// First, register the BeanPostProcessors that implement PriorityOrdered.
// 首先,注册实现PriorityOrdered的BeanPostProcessors。
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

// Next, register the BeanPostProcessors that implement Ordered.
// 接下来,注册实现Ordered的BeanPostProcessors。
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);

// Now, register all regular BeanPostProcessors.
// 现在,注册所有常规BeanPostProcessors。
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

// Finally, re-register all internal BeanPostProcessors.
// 最终,注册所有常规内部BeanPostProcessors。
sortPostProcessors(internalPostProcessors, beanFactory);
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).
// 将用于检测内部bean的后处理器重新注册为ApplicationListeners,
// 将其移动到处理器链的末端(用于拾取代理等)。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}

这里的解析与BeanFactoryPostProcessor的执行和解析很相似了,基本套路都是一样的。

  1. 通过getBeanNamesByType 获取BPP的数组
  2. 设置集合存储BPP
  3. 按照顺序解析注册PriorityOrderedOrderdNoOrderdInternal的BPP
  4. ApplicationListenerDetector 注册到容器的后面,这个类是之前添加过的(这里:prepareBeanFactory),这里移到了最后

BFPP 不同的是,BPP只是进行了注册并没有进行执行,BFPP是注册并执行。

参考:

https://www.cnblogs.com/redwinter/p/16198942.html

https://www.cnblogs.com/redwinter/p/16229572.html