SpringBoot 启动分析-refresh()

refresh()


上一篇分析 SpringBoot 启动过程中的 构造过程及 run(),在构造的过程中,主要是根据应用程序的类型设置 WebApplicationType,同时根据 spring.factories的配置读取初始化容器的一些监听器 listeners 和初始化器 initializers

而在 run()中,主要是对应用上下文 ApplicationContext 创建并进行初始化,设置 WebApplicationType对应的 environment,然后 refreshContext(context) ,最后加载 listeners start(),running 并加入 SpringRunners.

refreshContext(context) 主要有下面几个工作:

  1. prepareRefresh()
  2. prepareBeanFactory()
  3. postProcessBeanFactory()
  4. invokeBeanFactoryPostProcessors()
  5. registerBeanPostProcessors()
  6. initMessageSource()
  7. initApplicationEventMulticaster()
  8. onRefresh()
  9. registerListeners()
  10. finishBeanFactoryInitialization()
  11. finishRefresh()

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
  public void refresh() throws BeansException, IllegalStateException {
// 获取监视器锁
synchronized(this.startupShutdownMonitor) {

// 刷新上下文前的准备,记录状态,验证必要属性
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();

// 配置标准的 beanFactory,设置 classloader, bean表达解析器,同时注册重要的bean组件
this.prepareBeanFactory(beanFactory);

try {
// 模板方法,交由子类对 beanFactory 进行后置处理
this.postProcessBeanFactory(beanFactory);

// 调用 beanFactoryPostPorcessor
this.invokeBeanFactoryPostProcessors(beanFactory);

// 注册容器中的 beanPostProcessors
this.registerBeanPostProcessors(beanFactory);

// 初始化国际工具类 MessageSource
this.initMessageSource();

// 初始化并注册事件广播器 ApplicationEventMulticaster
this.initApplicationEventMulticaster();

// 模板方法,根据应用的具体类型交由子类具体处理,如果是web类型,通常是构建webServer
this.onRefresh();

// 注册容器中的监听器,包括spring.factories 和 自定义 bean listenr
this.registerListeners();

// 实例化所有的单例 bean (非 Lazy),beanPostProcessor 开始起作用
this.finishBeanFactoryInitialization(beanFactory);

// refresh() 后的额外工作,包括清除resource cahce,注册 LifeCycleProcessor及发布上下文已经刷新的事件 ContexntRefreshedEvent
this.finishRefresh();
} catch (BeansException var9) {

// 如果刷新上下文的过程中,出现异常,那么销毁所有已经创建的 bean
this.destroyBeans();

// 重置 context 的刷新状态,即将 active = false
this.cancelRefresh(var9);
throw var9;
} finally {
// 无论失败与否,已经不再需要 bean metadata,重置 Spring 的内核缓存
this.resetCommonCaches();
}
}
}


prepareRefresh()

prepareRefresh() 是为 refresh() 进行了准备工作,主要准备工作有:

  1. 记录 Spring 容器的启动时间,同时设置 active , closed 的状态

  2. 初始化属性源信息 (propertySources),及验证当前环境中的必要的属性是否存在

  3. 设置 earlyApplicationListeners & earlyApplicationEvents 属性列表

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 prepareRefresh() {
// 记录启动时间
this.startupDate = System.currentTimeMillis();

// 设置关闭状态,及开启状态
this.closed.set(false);
this.active.set(true);

// 初始化属性源信息
this.initPropertySources();

// 验证当前环境中的必要属性是否存在
this.getEnvironment().validateRequiredProperties();

// 判断 earlyApplicationListeners 是否存在,是的话加入到应用程序监听器 ApplicationListeners中,
// 否则的话创建新的对象
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
} else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}

// 创建 earlyApplicationEvents
this.earlyApplicationEvents = new LinkedHashSet();
}


prepareBeanFactory()

prepareBeanFactory() 获取了容器中的 beanFactory 并进行以下操作:

  1. 设置 bean 加载器 BeanClassLoader(用于 Bean 的加载),bean 表达式解析器 BeanExpressionResolver
  2. 添加注册属性编辑器 propertyEditorRegistrar,添加 BeanPostProcessor (ApplicationContextAwareProcessor)
  3. 将几个重要的 bean ( BeanFactory, ResourceLoader, ApplicationEventPublisher, ApplicationContext ) 加载到容器中,后续使用
  4. 添加 ApplicationListenerDetector 到 beanFactory 中的 beanPostProcessor 列表中
  5. 检查并注入其他的属性信息,如 loadTimeWeaver, environment 等
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
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置 beanClassLoader
beanFactory.setBeanClassLoader(this.getClassLoader());

// 设置 bean 表达解析器(用于处理定义 Bean 过程中的一些解析表达式: 例如 #{sqlProperties} )
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

// 添加注册属性编辑器
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));

// 添加 ApplicationContextAwareProcessor 到 beanPostProcessors 列表中
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

/** 取消 EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware,
* AApplicationEventPublisherAware, MessageSourceAware, ApplicationContextAware
* 这些接口的依赖注入,因为这些接口的属性设置工作已经被 ApplicationContextAwareProcessor代替
*
* 这些接口将会保存在 beanFactory 中的 ignoredDependencyInterfaces 列表中
*/
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

// 添加重要的 bean 到容器中,BeanFactory, ResourceLoader,
ApplicationEventPublisher, ApplicationContext
这里可以设置为 this,是因为都实现了对应接口中的方法

这些类属性将会被保存在 beanFactory 中的 resolvableDependencies map表中
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

// 添加 ApplicationListenerDetector 到 beanFactory 中的 beanPostProcessors 列表中
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));


// 检查代码织入,通常用于 Aspect切面的准备工作
if (beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}

// 检查并设置 localBean,environment, systemProperties, systemEnvironment
if (!beanFactory.containsLocalBean("environment")) {
beanFactory.registerSingleton("environment", this.getEnvironment());
}

if (!beanFactory.containsLocalBean("systemProperties")) {
beanFactory.registerSingleton("systemProperties", this.getEnvironment().getSystemProperties());
}

if (!beanFactory.containsLocalBean("systemEnvironment")) {
beanFactory.registerSingleton("systemEnvironment", this.getEnvironment().getSystemEnvironment());
}
}


// ApplicationContextAwareProcessor extend BeanPostProcessor
// 在 postProcessBeforeInitialization()的时候,调用 invokeAwareInterfaces
// 根据 bean 的类型设置对应接口的属性信息
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware)bean).setEnvironment(this.applicationContext.getEnvironment());
}

if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware)bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}

if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware)bean).setResourceLoader(this.applicationContext);
}

if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware)bean).setApplicationEventPublisher(this.applicationContext);
}

if (bean instanceof MessageSourceAware) {
((MessageSourceAware)bean).setMessageSource(this.applicationContext);
}

if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
}
}

}


postProcessBeanFactory()

postProcessBeanFactory() 主要是对设置属性后的 beanFactory 进行了后续的操作, 不同的应用程序类型会由不同的类进行操作,例如在 Servlet 类型中,对应的操作类为 AnnotationConfigServletWebServerApplicationContext, 而在 Reactive 中对应的则是 AnnotationConfigReactiveWebServerApplicationContext,区别在于调用的父类方法 postProcessBeanFactory()上,而读取注册 basePackages、annotatedClass 属性上的 bean 组件都是相同的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// AnnotationConfigReactiveWebServerApplicationContext.class 
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 调用父类 AbstractApplicationContext的方法实现
super.postProcessBeanFactory(beanFactory);

// 如果设置了 basePackages 属性,那么调用 ClassPathBeanDefinitionScanner 扫描 basePackages 下的bean组件,并注册到容器中
if (!ObjectUtils.isEmpty(this.basePackages)) {
this.scanner.scan(this.basePackages);
}

// 如果设置了 annotatedClasses 属性,那么调用 AnnotatedBeanDefinitionReader 注册这些带注解的bean信息
if (!this.annotatedClasses.isEmpty()) {
this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
}

}


invokeBeanFactoryPostProcessors()

  1. BeanFactoryPostProcessors 可以对容器中加载 bean,进行属性修改,这里得bean 还未实例化,更没有初始,允许修改 bean 定义
  2. BeanDefinitionRegistryPostProcessor 是对于 BeanFactoryPostProcessor 的扩展,允许修改 bean 注册器,也就是说可以在 BeanFactoryPostProcessor 之前对 bean 进行定义的修改
1
2
3
4
5
6
7
8
@FunctionalInterface
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory var1) throws BeansException;
}

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry var1) throws BeansException;
}


invokeBeanFactoryPostProcessors() 主要是调用获取当前容器中得 beanPostProessor ( BeanFactoryPostProcessor & BeanDefinitionRegistryPostProcessor ) ,根据 postProcessor 的接口实现 PriorityOrdered & Ordered 进行排序并调用,实现逻辑中 beanDefinitionRegistryPostProcessor 会在 beanFactoryPostProcessor 之前进行调用,保证了两种接口之间的调用顺序.

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
// 具体的调用过程被委托到 PostProcessorRegistrationDelegate.class 下
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

// 创建集合 processedBeans 用于保存所有处理过的 postProcessor name
Set<String> processedBeans = new HashSet();

// 定义两个列表分别存放 beanFactoryPostProcessor & beanDefinitionRegistryPostProcessor
ArrayList regularPostProcessors;
ArrayList registryProcessors;
int var9;
ArrayList currentRegistryProcessors;
String[] postProcessorNames;

// 如果 beanFactory 属于 beanDefinitionRegistry 的时候,遍历 beanFactoryPostProcessors,区分存储 到 regulatPostProcessors & registryProcessors
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory;
regularPostProcessors = new ArrayList();
registryProcessors = new ArrayList();
Iterator var6 = beanFactoryPostProcessors.iterator();

// registryPostPorcessors -> BeanDefinitionRegistryPostProcessor
// regulatPostProcessors -> BeanFactoryPostProcessor
while(var6.hasNext()) {
BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor)var6.next();
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor)postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
} else {
regularPostProcessors.add(postProcessor);
}
}

// 获取所有类型为 BeanDefinitionRegistryPostProcessor 的 bean name
currentRegistryProcessors = new ArrayList();
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
String[] var16 = postProcessorNames;
var9 = postProcessorNames.length;

// 先筛选出实现 PriorityOrdered 接口的 beanDefinitionRegistryPostProcessor,
并保存在集合 currentRegistryProcessors, processedBeans 中
int var10;
String ppName;
for(var10 = 0; var10 < var9; ++var10) {
ppName = var16[var10];
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}

// 根据 priorityOrdered 的优先级进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);

// 遍历调用执行所有的 PriorityOrdered BeanDefinitionRegistryProcessors
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
var16 = postProcessorNames;
var9 = postProcessorNames.length;

// 重新获取并筛选出实现 Ordered 接口的 BeanDefinitionRegistryPostProcessors
for(var10 = 0; var10 < var9; ++var10) {
ppName = var16[var10];
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 根据 Ordered 优先级排序,然后遍历调用
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
boolean reiterate = true;

// 找到其余的 BeanDefinitionRegistryPostProcessor, 进行排序并注册调用
while(reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
String[] var19 = postProcessorNames;
var10 = postProcessorNames.length;

for(int var26 = 0; var26 < var10; ++var26) {
String ppName = var19[var26];
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();
}

// 因为 BeanDefinitionRegistryPostProcessors 实现了 BeanFactoryPostProcessor 中的方法,
所以这里调用在接口中实现的 postProcessBeanFactory()
invokeBeanFactoryPostProcessors((Collection)registryProcessors, (ConfigurableListableBeanFactory)beanFactory);
invokeBeanFactoryPostProcessors((Collection)regularPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
} else {

// 如果当前 beanFactroy 不是 beanDefinitionRegistry,则直接执行 BeanFactoryPostProcessor 接口
invokeBeanFactoryPostProcessors((Collection)beanFactoryPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
}


// 接着就是获取所有类型为 BeanFactoryPostProcessor 的 bean name
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// 复用集合,用 regularPostProcessors 存储实现接口 PriorityOrdered 的 beanFactoryPostProcessor,
用 registeyProcessors 存储是新建接口 Ordered 的 beanFactoryPostProcessor
regularPostProcessors = new ArrayList();
registryProcessors = new ArrayList();
currentRegistryProcessors = new ArrayList();
postProcessorNames = postProcessorNames;
int var20 = postProcessorNames.length;

// 遍历根据实现的接口进行分组
String ppName;
for(var9 = 0; var9 < var20; ++var9) {
ppName = postProcessorNames[var9];
if (!processedBeans.contains(ppName)) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
regularPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
registryProcessors.add(ppName);
} else {
currentRegistryProcessors.add(ppName);
}
}
}

// 重排序实现接口 PriorityOrdered 的 beanFactoryPostProcessors,遍历并调用执行
sortPostProcessors(regularPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors((Collection)regularPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList();
Iterator var21 = registryProcessors.iterator();

while(var21.hasNext()) {
String postProcessorName = (String)var21.next();
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}

// 重排序实现接口 Ordered 的 beanFactoryPostProcessors,遍历并调用执行
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors((Collection)orderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList();
Iterator var24 = currentRegistryProcessors.iterator();

while(var24.hasNext()) {
ppName = (String)var24.next();
nonOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}

// 遍历调用其余没有实现排序接口的 beanFactoryPostProcessor
invokeBeanFactoryPostProcessors((Collection)nonOrderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);

// 清空缓存
beanFactory.clearMetadataCache();
}


registerBeanPostProcessors()

registerBeanPostProcessors() 主要是找到容器中的 BeanPostProcessor 类型的 bean,根据具体的实现 PriorityOrdered,Ordered, 进行分类并排序,然后注册到 beanFactory 中的属性列表中,具体的实现被 AbstractApplicationContext 交由 PostProcessorRegistrationDelegate.registerBeanPostProcessors 实现。

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

// 获取所有类型为 BeanPostProcessor 的 postProcessorNames
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 统计总数
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;

// 在 beanFactory 中添加 PostProcessorRegistrationDelegate 委托类的子类 BeanPostProcessorChecker 检查类,用于在 beanPostProcessor 实例化期间,当 bean 被创建时打印信息
beanFactory.addBeanPostProcessor(new PostProcessorRegistrationDelegate.BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// 构建列表 priorityOrderedPostProcessors, internalPostProcessors,
orderedPostProcessorNames, nonOrderedPostProcessorNames,用于存储不同类型的 postProcessor
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList();
List<BeanPostProcessor> internalPostProcessors = new ArrayList();
List<String> orderedPostProcessorNames = new ArrayList();
List<String> nonOrderedPostProcessorNames = new ArrayList();
String[] var8 = postProcessorNames;
int var9 = postProcessorNames.length;

// 遍历 beanPostProcessor name array,根据 beanPostProcessor 的具体类型进行分类
String ppName;
BeanPostProcessor pp;
for(int var10 = 0; var10 < var9; ++var10) {
ppName = var8[var10];
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
} else {
nonOrderedPostProcessorNames.add(ppName);
}
}

// 加载实现 PriorityOrdered 接口的 beanPostProcessors,根据优先级进行排序,然后对 priorityOrderedPostProcessors 进行遍历注册到 beanFactory
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, (List)priorityOrderedPostProcessors);

// 加载实现 Ordered 接口的 beanPostProcessors,排序后遍历注册到 beanFactory 中
List<BeanPostProcessor> orderedPostProcessors = new ArrayList();
Iterator var14 = orderedPostProcessorNames.iterator();

while(var14.hasNext()) {
String ppName = (String)var14.next();
BeanPostProcessor pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}

sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, (List)orderedPostProcessors);

// 加载剩余未实现 ordered 的 beanPostProcessors, 遍历并加载到 beanFactory 中
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList();
Iterator var17 = nonOrderedPostProcessorNames.iterator();

while(var17.hasNext()) {
ppName = (String)var17.next();
pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}

registerBeanPostProcessors(beanFactory, (List)nonOrderedPostProcessors);
sortPostProcessors(internalPostProcessors, beanFactory);

// 遍历注册内部后置处理器 internalPostProcessors,
registerBeanPostProcessors(beanFactory, (List)internalPostProcessors);

// 重新注册 用于检查内部bean 的 postProcessor (ApplicationListenerDetector),
// 将这个检查处理器重新移动到 processors chain 末尾
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}


initMessageSource()

MessageSource 是 Spring 支持国际化的一种方式,通过 MessageSource,可以读取根据 Locale 的具体位置设置,自动选择对应的 messages.properties (messages_en.properties, messages_ch_properties) 配置文件。然后根据业务需求 getMessage() 的到我们要的配置信息。

而 initMessageSource() 的作用就在于读取 messageSource bean,并进行初始化

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
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();

// 判断本地是否存在 messageSource bean
if (beanFactory.containsLocalBean("messageSource")) {
this.messageSource = (MessageSource)beanFactory.getBean("messageSource", MessageSource.class);

// 如果属于 HierarchicalMessageSource (可用于处理分层 messageSource),那么设置父属性
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource)this.messageSource;
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(this.getInternalParentMessageSource());
}
}
} else {

// 否则创建一个新的对象
DelegatingMessageSource dms = new DelegatingMessageSource();

// 然后属性设置
dms.setParentMessageSource(this.getInternalParentMessageSource());
this.messageSource = dms;

// 最后,将 messageSource 作为一个单例的 bean 注册到 beanFactory 中
beanFactory.registerSingleton("messageSource", this.messageSource);
}
}


initApplicationEventMulticaster()

通常,我们在 Spring 中 发送一个事件 event 是采用 applicationContext.pushEvent() ,实际上,具体的事件发送广播是被交由 applicationEventMulticaster 发送,具体的过程将后续将会出一篇 Spring Event 事件机制进行介绍。而 initApplicationEventMulticaster() 就是将 applicationEventMulticater 注册到 beanFactory 容器中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// AbstractApplicationContext.class
protected void initApplicationEventMulticaster() {

// 获取 beanFactory,判断本地是否存在 bean 组件 applicationEventMulticaster
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (beanFactory.containsLocalBean("applicationEventMulticaster")) {
this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
...

} else {

// 如果本地不存在,则实例化一个 simpleApplicationEventMulticaster,并且单例注册到 beanfactory
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster);
...
}

}


onRefresh()

onRefresh() 和上面的 postProcessBeanFactory() 一样,都是一个模板方法,具体的实现会根据 webApplicationType 的具体类型找到对应的 GenericWebApplicationContext || ReactiveWebServerApplicationContext 等,具体实现都有所不同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// AbstractApplicationContext.class
protected void onRefresh() throws BeansException {
}

// GenericWebApplicationContext.class
// 具体过程是初始化主题
protected void onRefresh() {
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

// ServletWebServerApplicationContext.class // ReactiveWebServerApplicationContext
// 具体过程是构建一个 servlet webServer
protected void onRefresh() {
super.onRefresh();

try {
this.createWebServer();
} catch (Throwable var2) {
throw new ApplicationContextException("Unable to start web server", var2);
}
}


registerListeners()

在上面的步骤中,我们已经将事件广播器 applicationEventMulticaster 注册到了容器中,有了广播器,那么接下来就是收集容器中的所有 listener bean 组件,将他们保存在集合中,以便事件发布时能够遍历监听器列表,通过适配 eventType,找到对应的 listener 并进行处理。

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
// AbstractApplicationContext.class
protected void registerListeners() {
// 获取监听器 listeners 集合,这里的 listeners 是各个模块中的 spirng.factories 中的 listeners
Iterator var1 = this.getApplicationListeners().iterator();

// 遍历listeners ,加入到 AbstractApplicationEventListeners中的 applicationListeners 集合中
while(var1.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var1.next();
this.getApplicationEventMulticaster().addApplicationListener(listener);
}

// 获取所有监听器的名称,并遍历加入到 AbstractApplicationEventListeners applicationListenerBeans // 这里的 listeners 指的是容器中实现了 ApplicationListener 的 bean 组件
// 包括了我们自定义的 listener 或者是 spring中定义的 @Bean mvcResourceUrlProvider
String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);
String[] var7 = listenerBeanNames;
int var3 = listenerBeanNames.length;

for(int var4 = 0; var4 < var3; ++var4) {
String listenerBeanName = var7[var4];
this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}

// 如果存在早期事件,那么直接发布出去
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
Iterator var9 = earlyEventsToProcess.iterator();

while(var9.hasNext()) {
ApplicationEvent earlyEvent = (ApplicationEvent)var9.next();
this.getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}


finishBeanFactoryInitialization()

finishBeanFactoryInitialization(beanFactory) 的主要作用是实例化所有的单例 bean ( 非 Lazy ),这个时候,容器中的 beanPostProcessor 将会开始起作用。

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
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化 context 的转换服务, conversionService 是一个类型转换接口,可实现自定义类型间的转换
if (beanFactory.containsBean("conversionService") && beanFactory.isTypeMatch("conversionService", ConversionService.class)) {
beanFactory.setConversionService((ConversionService)beanFactory.getBean("conversionService", ConversionService.class));
}

// 注册内置的值处理器,用于对 property 进行处理(例如占位符处理)
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver((strVal) -> {
return this.getEnvironment().resolvePlaceholders(strVal);
});
}

// 获取 LoadTimeWeaverAware Bean
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
String[] var3 = weaverAwareNames;
int var4 = weaverAwareNames.length;

for(int var5 = 0; var5 < var4; ++var5) {
String weaverAwareName = var3[var5];
this.getBean(weaverAwareName);
}

// 停止使用临时的类加载器
beanFactory.setTempClassLoader((ClassLoader)null);

// 缓存所有的 beanDefinition 数据,防止更改,实际上是将 beanDefinitionNames 进行备份
// this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames)
beanFactory.freezeConfiguration();

// 实例化所有的单例的bean (非 Lazy)
beanFactory.preInstantiateSingletons();
}


finishRefresh()

finishRefresh() 的作用是做 refesh() 后的额外操作,例如清除上下文缓存 ( ASM 数据 ),初始化 生命周期处理器 LifeCycleProcessor,发布 上下文已经刷新事件 ContextRefreshedEvent.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
AbstractApplicationContext.class
protected void finishRefresh() {
// 清除 context level 的资源缓存,例如扫描中的 ASM 数据
this.clearResourceCaches();

// 初始化 LifeCycleProcessor,和 initApplicationEventMulticaster 差不多,先检查本地,否者创建注册
this.initLifecycleProcessor();

// 调用所有 LifeCycleBean 的 start()
this.getLifecycleProcessor().onRefresh();

// 完成上下文刷新后,发布 ContextRefeshedEvent 上下文刷新事件
this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this)));

// 如果设置了 JMX 属性,那么将进行注册
LiveBeansView.registerApplicationContext(this);
}

总结

可以看出,refresh() 在 SpringBoot 的启动过程中,扮演着非常重要的角色,包括了注册重要的 bean 组件,实例化容器中的 bean,processors 之间的调用等,通过分析后,我们可以了解到了我们日常工作中使用到的各种实现例如 InstantiationAwareBeanPostProcessor ,Listener, LifeCycleProcessor 等组件的调用顺序及功能。

同时,refresh() 过程也很好的展示了 bean 的生命周期中各个组件的位置及作用,也对于我们理解 Spring 容器有了更好的理解。

引用