通过分析ClassPathXmlApplicationContext 的源代码可以知道, 在创建ClassPathXmlApplicationContext 容器时,构造方法做以下两项重要工作:
首先,调用父类容器的构造方法(super(parent)方法)为容器设置好Bean 资源加载器。
然后, 再调用父类AbstractRefreshableConfigApplicationContext 的setConfigLocations(configLocations)方法设置Bean 配置信息的定位路径。
通过追踪ClassPathXmlApplicationContext 的继承体系, 发现其父类的父类AbstractApplicationContext 中初始化IOC 容器所做的主要源码如下:
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
//静态初始化块,在整个容器创建过程中只执行一次
static {
//为了避免应用程序在Weblogic8.1 关闭时出现类加载异常加载问题,加载IOC 容
//器关闭事件(ContextClosedEvent)类
ContextClosedEvent.class.getName();
}
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
//获取一个Spring Source 的加载器用于读入Spring Bean 配置信息
protected ResourcePatternResolver getResourcePatternResolver() {
//AbstractApplicationContext 继承DefaultResourceLoader,因此也是一个资源加载器
//Spring 资源加载器,其getResource(String location)方法用于载入资源
return new PathMatchingResourcePatternResolver(this);
}
...
}
AbstractApplicationContext 的默认构造方法中有调用PathMatchingResourcePatternResolver 的构造方法创建Spring 资源加载器:
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
//设置Spring的资源加载器
this.resourceLoader = resourceLoader;
}
在设置容器的资源加载器之后,接下来ClassPathXmlApplicationContext 执行setConfigLocations()方法通过调用其父类AbstractRefreshableConfigApplicationContext 的方法进行对Bean 配置信息的定位,该方法的源码如下:
/**
* Set the config locations for this application context in init-param style,
* i.e. with distinct locations separated by commas, semicolons or whitespace.
* <p>If not set, the implementation may use a default as appropriate.
*/
//处理单个资源文件路径为一个字符串的情况
public void setConfigLocation(String location) {
//String CONFIG_LOCATION_DELIMITERS = ",; /t/n";
//即多个资源文件路径之间用” ,; \t\n”分隔,解析成数组形式
setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}
/**
* Set the config locations for this application context.
* <p>If not set, the implementation may use a default as appropriate.
*/
//解析Bean定义资源文件的路径,处理多个资源文件字符串数组
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++) {
// resolvePath为同一个类中将字符串解析为路径的方法
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
通过这两个方法的源码我们可以看出,我们既可以使用一个字符串来配置多个Spring Bean 配置信息,也可以使用字符串数组,即下面两种方式都是可以的:
ClassPathResource res = new ClassPathResource("a.xml,b.xml");
多个资源文件路径之间可以是用” , ; \t\n”等分隔。
ClassPathResource res =new ClassPathResource(new String[]{"a.xml","b.xml"});
至此,SpringIOC 容器在初始化时将配置的Bean 配置信息定位为Spring 封装的Resource。