一、结论
1. 目标结论
refresh方法是初始化Spring容器的核心代码,共分为12个步骤
2. 其他结论
设计思想:
- 抽象思维锻炼
代码风格:
- 代码应该有个好名字。起不了好名字,有可能是违反了单一职责
- javadoc文档。
- Spring源码的习惯utils使用abstract class,虽然平时大家都不会去new,但谁知道呢,“可能会/一定不会”
- …
二、找线索
官方文档线索
官方文档摘录
The org.springframework.beans
and org.springframework.context
packages are the basis for Spring Framework’s IoC container. The BeanFactory
interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext
is a sub-interface of BeanFactory
.
The org.springframework.context.ApplicationContext
interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.
Several implementations of the ApplicationContext
interface are supplied with Spring. In stand-alone applications, it is common to create an instance of ClassPathXmlApplicationContext
or FileSystemXmlApplicationContext
.
这里说明我们应该关注org.springframework.beans
和org.springframework.context
两个包,核心接口BeanFactory
和ApplicationContext
。
可以初步确定研究对象 ClassPathXmlApplicationContext
和FileSystemXmlApplicationContext
这两个实现类。
源码层线索
org.springframework.context
包下ApplicationContext
的实现
在org.springframework.context
包下创建IOC容器的方式:
- ClassPathXmlApplicationContext:从classpath中加载配置文件;
- FileSystemXmlApplicationContext:从磁盘中加载配置文件;
- AnnotationConfigApplicationContext:使用注解配置容器对象时,使用此类进行注解读取,创建容器;
三、源码分析
ClassPathXmlApplicationContext 类图
ClassPathXmlApplicationContext源码
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {
configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
// ApplictionContext继承了HierarchicalBeanFactory,可以竖向竖向扩展
super(parent);
setConfigLocations(configLocations);
if (refresh) {
// 刷新IoC容器,这里调用的父类AbstractApplicationContext中的refresh实现
refresh();
}
}
AbstractApplicationContext源码
@Override
public void refresh() throws BeansException, IllegalStat