AbstractApplicationContext的refresh流程

AbstractApplicationContextApplicationContext 的一个抽象实现类。和普通的 BeanFactory 不同的是,ApplicationContext 可以检测到它的内部 BeanFactory 中定义的特殊 Bean:自动完成 BeanFactoryPostProcessorBeanPostProcessorApplicationListener 的注册。

按照惯例,先来看下 AbstractApplicationContext 的继承结构,嗯,你会发现挺复杂的

image-20200411182520072

不过不要紧,我们只关心它的 refresh 方法实现。refresh 方法来自 ConfigurableApplicationContext 接口,关于它的功能描述如下:

加载或刷新配置的持久化,这些配置可以来自 XML 文件、properties 文件、关心数据库等等。因为该方法是一个启动方法,如果失败了,它应该销毁已经创建的单例,以避免出现悬挂资源(dangling resources),换句话说,要么实例化所有的单例,要么一个也不实例化。

refresh 代码跟踪

接下来看下 refresh 方法的实现。

prepareRefresh

这里是做一些准备工作,包括设置开始时间、active 状态、PropertySources 的初始化等等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);

// Initialize any placeholder property sources in the context environment
initPropertySources();

// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();

// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}

obtainFreshBeanFactory

告诉子类刷新内部的 BeanFactory,然后返回刷新后的 BeanFactory

1
2
refreshBeanFactory();
return getBeanFactory();

GenericApplicationContext 中的 refreshBeanFactory 实现如下:

1
2
3
4
5
6
7
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}

它只是设置下 SerializationId,实际的 beanFactory 初始化是在创建时完成的

1
2
3
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}

当然 refreshBeanFactory 也可以有其他的实现方式。

getBeanFactory 比较简单,就是返回已创建的 beanFactory

prepareBeanFactory

配置 BeanFactory 的标准 context 特征,例如设置 context 的 class loader 和 post processor

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
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 内部的 BeanFactory 使用 context 的 class loader
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

// 这家伙就是用来处理 Aware 接口的
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 忽略这些 Aware 接口,BeanFactory 中有单独的处理逻辑
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 中定义的 bean,需要特殊处理
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.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

// Detect a LoadTimeWeaver and prepare for weaving, if found.
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()));
}

// 注册默认的环境相关的 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());
}
}

postProcessBeanFactory

对 BeanFactory 进行后处理,默认的实现为空,交给子类去扩展。可以对 beanFactory 进行想要的操作。比如 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);
}

invokeBeanFactoryPostProcessors

调用 BeanFactoryPostProcessor

1
2
3
4
5
6
7
8
9
10
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
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)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}

首先通过 getBeanFactoryPostProcessors 方法取出已经注册到 BeanFactory 中的所有BeanFactoryPostProcessor,然后交给 invokeBeanFactoryPostProcessors 方法去处理

处理流程

主要分为两个阶段:首先处理 BeanDefinitionRegistryPostProcessor 接口的回调,然后处理 BeanFactoryPostProcessor 接口的回调

BeanDefinitionRegistryPostProcessor 接口回调

这是第一个阶段,处理实现了 BeanDefinitionRegistryPostProcessor 接口的 bean 的回调。

判断 beanFactory 是否为 BeanDefinitionRegistry 类型的实例

是 BeanDefinitionRegistry 类型的实例

首先处理方法入参中传入的 beanFactoryPostProcessors,分别调用其 postProcessBeanDefinitionRegistry 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 是 BeanDefinitionRegistryPostProcessor
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 调用 postProcessBeanDefinitionRegistry 方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
// 是普通的 BeanFactoryPostProcessor,留作后面统一处理
else {
regularPostProcessors.add(postProcessor);
}
}

然后从 beanFactory 中获取所有实现了 BeanDefinitionRegistryPostProcessor 接口和 PriorityOrdered 接口的 bean,分别调用其 postProcessBeanDefinitionRegistry 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 取出所有实现了 BeanDefinitionRegistryPostProcessor接口的beanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 如果还实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 取出bean
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);

// 调用postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清理
currentRegistryProcessors.clear();

接着是 beanFactory 中实现了 BeanDefinitionRegistryPostProcessor 接口和 Ordered 接口的 bean,分别调用其 postProcessBeanDefinitionRegistry 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 取出所有实现了 BeanDefinitionRegistryPostProcessor接口的beanName
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 如果还未处理过,并且实现了Ordered接口
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 取出bean
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 调用postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();

最后是其他实现了 BeanDefinitionRegistryPostProcessor 接口且还未处理过的 bean,分别调用其 postProcessBeanDefinitionRegistry 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
boolean reiterate = true;
while (reiterate) {
reiterate = false;
// 取出所有实现了 BeanDefinitionRegistryPostProcessor接口的beanName
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 只要是还未处理过的
if (!processedBeans.contains(ppName)) {
// 取出bean
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 排序
registryProcessors.addAll(currentRegistryProcessors);
// 调用postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}

因为 BeanDefinitionRegistryPostProcessor接口 继承自 BeanFactoryPostProcessor 接口,所以还需要回调 BeanFactoryPostProcessor 接口的 postProcessBeanFactory 方法

1
2
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
不是 BeanDefinitionRegistry 类型的实例

这个就比较简单了,直接调用 BeanFactoryPostProcessorpostProcessBeanFactory 方法

1
2
3
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}

BeanFactoryPostProcessor 接口回调

这里说的 BeanFactoryPostProcessor 不包括接口入参的 beanFactoryPostProcessors,因为在上一步已经处理过了。也不包括 beanFactory 中实现了 BeanDefinitionRegistryPostProcessor 接口的 bean,这种情况也在上一步处理过了。

首先还是要从 beanFactory 中取出所有实现了 BeanFactoryPostProcessor 接口的 beanName

1
2
3
// 取出所有的BeanFactoryPostProcessor的beanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

按照是否实现了 PriorityOrderedOrdered 接口分为 3 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// 忽略已经在第一阶段被postProcessBeanDefinitionRegistry处理过的
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 实现了PriorityOrdered接口的
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 实现了Ordered接口的
orderedPostProcessorNames.add(ppName);
}
else {
// 未实现优先级接口的
nonOrderedPostProcessorNames.add(ppName);
}
}

先回调实现了 PriorityOrdered 接口的

1
2
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

接着是回调实现了 Ordered 接口的

1
2
3
4
5
6
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

最后是未实现优先级接口的

1
2
3
4
5
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

registerBeanPostProcessors

实例化并且调用所有已注册的 BeanPostProcessor

获取所有实现了 BeanPostProcessor 接口的 beanName

1
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

按照是否实现了 PriorityOrderedOrdered 接口分为 3 类,实现了 MergedBeanDefinitionPostProcessor 接口单独拎出来,用于特殊处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);

// MergedBeanDefinitionPostProcessor 接口由 spring 内部处理
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}

先注册所有实现了 PriorityOrdered 接口的

1
2
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

再注册实现了 Ordered 接口的

1
2
3
4
5
6
7
8
9
10
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
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);

最后注册所有实现了 MergedBeanDefinitionPostProcessor 接口的

1
2
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);

initMessageSource

对 messageSource 进行初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// beanFactory 中已经注册过 messageSource 了
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
}
// 还未注册过
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
}

initApplicationEventMulticaster

初始化上下文中的事件机制

1
2
3
4
5
6
7
8
9
10
11
12
13
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// beanFactory 中已经注册过 applicationEventMulticaster
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
}
// 还未注册过
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
}
}

onRefresh

留给子类去实现,用于初始化其他特殊的 bean。比如 Spring Boot 中,ServletWebServerApplicationContext 就是在这一步去创建的 web server

1
2
3
4
5
6
7
8
9
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}

ServletWebServerApplicationContext 创建 web server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context",
ex);
}
}
initPropertySources();
}

registerListeners

检查 listener bean 并向容器注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 先注册 AbstractApplicationContext 中取到的
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}

// 不要在此初始化 FactoryBeans(最后一个参数设置为false),需要留给 post-processors 处理
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...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}

finishBeanFactoryInitialization

完成当前 context 的 beanFactory 的初始化,初始化剩下所有的 singleton 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
28
// 初始化 conversionService
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}

// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}

// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}

// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);

// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();

finishRefresh

完成当前 context 的 refresh 操作,调用 LifecycleProcessoronRefresh 方法,发布 ContextRefreshedEvent 事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();

// Initialize lifecycle processor for this context.
initLifecycleProcessor();

// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();

// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));

// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);

整体流程

整体流程如下图所示:

image-20200418012104632