一、ApplicationContext的理解
1.1 初步理解
首先要对ApplicationContext进行一定了解:
- 其主要解读为应用程序上下文
-
- 对Java程序来说,在运行测试类之前,首先要先加载程序的上下文,即进行加载程序需要的“运行环境”的配置
- 对Spring来说,如果要运行TestService这个Bean,就必须首先进行Spring环境配置,以此来配置TestService的上下文环境。
- 还有很重要的一点,源码解读过后,通过对ApplicationContext的理解逐渐加深,可以看出:
-
- ApplicationContext虽然继承自BeanFactory,但是它的执行过程中始终在内部实例化了一个BeanFactory,即一个DefaultListableBeanFactory,之后与BeanFactory相关的操作,都是通过该实例处理。
- 对该部分详细内容见下方3.1最后的分析
1.2 对Bean的理解
一直在说BeanFactory就是一个Bean容器,那如何理解Bean呢?
实际上,在代码层面,对开发者自己定义的bean,会被Spring转化为一个个BeanDefinition实例并存储在BeanFactory中。BeanDefinition的实例可以保存各种Bean信息。
二、ClassPathXmlApplicationContext源码解读
首先来看一下ClassPathXmlApplicationContext的源码:
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
@Nullable
private Resource[] configResources;
public ClassPathXmlApplicationContext() {
}
// 可以传入一个父类ApplicationContext,进行父子关系的配置
public ClassPathXmlApplicationContext(ApplicationContext parent) {
super(parent);
}
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
public ClassPathXmlApplicationContext(String[] configLocations, @Nullable ApplicationContext parent)
throws BeansException {
this(configLocations, true, parent);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
this(configLocations, refresh, null);
}
// 使用给定的父类创建一个新的ClassPathXmlApplicationContext,从给定的XML文件加载定义
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
// 源码见源码块一
setConfigLocations(configLocations);
// 调用refresh()方法重建 ApplicationContext,源码见源码块二:
if (refresh) {
refresh();
}
}
public ClassPathXmlApplicationContext(String path, Class> clazz) throws BeansException {
this(new String[] {path}, clazz);
}
public ClassPathXmlApplicationContext(String[] paths, Class> clazz) throws BeansException {
this(paths, clazz, null);
}
public ClassPathXmlApplicationContext(String[] paths, Class> clazz, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
Assert.notNull(paths, "Path array must not be null");
Assert.notNull(clazz, "Class argument must not be null");
this.configResources = new Resource[paths.length];
for (int i = 0; i < paths.length; i++) {
this.configResources[i] = new ClassPathResource(paths[i], clazz);
}
refresh();
}
@Override
@Nullable
protected Resource[] getConfigResources() {
return this.configResources;
}
}
源码块一:setConfigLocations方法源码
// 传入多个配置路径,然后存储在配置文件数组中
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;
}
}
源码块二:refresh方法源码
// 当已经创建了ApplicationContext后,可以通过refresh方法将原来的ApplicationContext销毁,然后重新执行初始化操作
@Override
public void refresh() throws BeansException, IllegalStateException {
// 给refresh操作加锁
synchronized (this.startupShutdownMonitor) {
// 为刷新上下文进行准备工作,设置它的启动日期、活动标志(即配置“已启动”状态),以及执行任何属性源的初始化。
prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
try {
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
// 最后一步:广播事件,ApplicationContext初始化完成
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 销毁操作:销毁已经初始化的Singleton Beans,避免有些bean会一直占用资源
destroyBeans();
cancelRefresh(ex);
throw ex;
}
finally {
resetCommonCaches();
}
}
}
三、第二层解读——refresh
接下来再对refresh()的各个方法进行解读
3.1 第一步:创建Bean容器前的准备工作
准备工作通过prepareRefresh()方法,源码如下:
protected void prepareRefresh() {
// 记录启动时间
this.startupDate = System.currentTimeMillis();
// 配置active和closed属性
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.
initPropertySources();
// 对xml配置文件进行校验
getEnvironment().validateRequiredProperties();
// 早期应用事件监听器,这个老版本的Spring是没有的
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 早期应用事件收集器
this.earlyApplicationEvents = new LinkedHashSet<>();
}
3.2 第二步:创建Bean容器,加载并注册Bean
注意:这部分是在初始化Bean之前,进行BeanFactory的初始化以及加载和注册Bean。
首先是obtainFreshBeanFactory()方法
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 创建新的或重置已有的BeanFactory,加载和注册Bean
refreshBeanFactory();
// 将全新的BeanFactory返回
return getBeanFactory();
}
该方法最主要的步骤就是通过refreshBeanFactory()方法来创建新的或重置已有的BeanFactory,加载和注册Bean。该方法的源码:
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
在AbstractApplicationContext中将其定义为一个抽象方法,让子类进行实现。继续找寻,从其子类AbstractRefreshableApplicationContext中找到该方法的一个实现,源码如下:
// 源码注释:
// 此实现执行此上下文的底层bean工厂的实际刷新,关闭以前的bean工厂(如果有)并为上下文生命周期的下一阶段初始化一个新的bean工厂。
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
// BeanFactory序列化
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
// 加载Bean到BeanFactory中
// 在AbstractXmlApplicationContext中有该函数的众多实现,很复杂
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
此处有一个细节点:为什么ApplicationContext实例化的是DefaultListableBeanFactory而不是其他的子类?
- 下图是一张网上的BeanFactory继承图,从中可以看出DefaultListableBeanFactory对绝大部分子接口都有直接或间接地继承,处于最底端的它涵盖了大部分BeanFactory子接口的特有属性。



