在 Spring 中,有两种方式加载配置文件:1、使用 BeanFactory 方式加载 XML;2、使用 ApplicationContext 加载 XML。第一种方式已经在之前的文章分析了,并深入了解了其内部机制。现在我们聊聊第二种方式,也是我们最为常用的一种方式 —— ApplicationContext。下面是 ApplicationContext 的启动部分。
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
配置文件以数组的方式传入,并通过 setConfigLocations
函数配置,而解析的全部工作都在 refresh
函数中实现。
设置配置路径
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
resolvePath
函数会解析数组中的内容,如 ${var} 会搜寻匹配的系统变量并替换。
扩展功能
refresh 函数十分清晰地为我们展现了加载及大致流程。
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备刷新上下文环境
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 初始化 BeanFactory,并进行 XML 文件读取
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 对 BeanFactory 进行各种功能填充
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 子类覆盖方法做额外处理
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 激活各种 BeanFactory 处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截 Bean 创建的 Bean 处理器,这里只是注册,真正调用是在 getBean 的时候
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 为上下文初始化 Message 源,即不同语言的消息体,国际化处理
initMessageSource();
// Initialize event multicaster for this context.
// 初始化应用消息广播器,并放入“applicationEventMulticaster” bean 中
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 留给子类来初始化其他的 Bean
onRefresh();
// Check for listener beans and register them.
// 在所有注册的 bean 中查找 Listener bean,注册到消息广播器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化剩下的单实例(非惰性)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 完成刷新过程,通知生命周期处理器 lifecycleProcessor 刷新过程
// 同时发出 ContextRefreshEvent 通知别人
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
下面概括一下上面函数的一些主要步骤:
- 初始化前的准备工作,例如对系统属性或者环境属性进行准备及验证
在某种情况下项目的使用需要读取某些系统变量,而这个变量的设置很可能会影响着系统的正确性,那么变量的验证就显得很重要了。 - 初始化 BeanFactory,并进行 XML 文件读取
这一步复用了 BeanFactory 对配置文件的读取解析及其他功能,这样 ApplicationContex 就已经包含了部分 BeanFactory 所提供的功能了。 - 对 BeanFactory 进行各种功能填充
- 子类覆盖方法做额外处理
获取扩展函数,如 postProcessBeanFactory。此处添加了对 @Qualifier 与 @Autowired 处理的相关 postProcesser。 - 激活各种 BeanFactory 处理器
- 注册拦截 Bean 创建的 Bean 处理器,这里只是注册,真正调用是在 getBean 的时候
- 为上下文初始化 Message 源,即不同语言的消息体,国际化处理
- 初始化应用消息广播器,并放入“applicationEventMulticaster” bean 中
- 留给子类来初始化其他的 Bean
- 在所有注册的 bean 中查找 Listener bean,注册到消息广播器中
- 初始化剩下的单实例(非惰性)
- 完成刷新过程,通知生命周期处理器 lifecycleProcessor 刷新过程,同时发出 ContextRefreshEvent 通知别人