Spring源码–ClassPathXmlApplicationContext

概述

ClassPathXmlApplicationContext对于学习spring的小伙伴一定是不陌生的,刚才 学的时候基本都会有遇到下面这段代码:

ApplicationContext applicationContext= new ClassPathXmlApplicationContext("x.xml");
B b=applicationContext.getBean(B.class);

官方的描述:单独xml application容器,从类文件路径上读取出容器信息,(Standalone XML application context, taking the context definition files from the class path)。

spring可以通过创建ApplicationContext容器可以实现对于bean的操作,而实现ApplicationContext接口的实现类就是ClassPathXmlApplicationContext类,这里使用多态的特性。但是具体实现是什么?需要对于源码进行解析,下面是对源码的解析。

源码

public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {

@Nullable
private Resource[] configResources;
/**
* 重构的构造方法
*/
public ClassPathXmlApplicationContext() {
}
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);
}
//构造方法实际的实现方法
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {

super(parent);
setConfigLocations(configLocations);
if (refresh) {
//进入核心的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;
}
}

上述源码核心的实现方式是执行了refresh()方法。refresh()是spring代码运转的核心,这个稍后会详细解释。