IOC 容器的初始化包括 BeanDefinition 的 Resource 定位、载入和注册这三个基本的过程。
以 ApplicationContext 为例讲解,ApplicationContext 系列容器也许是我们最熟悉的,因为 Web 项 目 中 使 用 的XmlWebApplicationContext 就 属 于 这 个 继 承 体 系 , 还 有 ClasspathXmlApplicationContext 等,其继承体系如下图所示:
以ClassPathXmlApplicationContext为例:
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
//初始化父类
super(parent);
//设置本地的配置信息,创建环境对象ConfigurableEnvironment 、处理ClassPathXmlApplicationContext传入的字符串中的占位符;
setConfigLocations(configLocations);
//完成Spring容器初始化
if (refresh) {
refresh();
}
}
//初始化父类
super(parent);
AbstractXmlApplicationContext类:
public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
AbstractRefreshableConfigApplicationContext类:
public AbstractRefreshableConfigApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
AbstractRefreshableApplicationContext类:
public AbstractRefreshableApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
AbstractApplicationContext类:
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
继承体系视图如下所示: