回到我们的代码之中,当我们 new ClassPathXmlApplicationContext()时,就代表着在创建一个普通环境上下文,在其构造器中打下断点,我们跟随着断点一步步来往下看;
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
//依次调用父类构造器,初始化默认一些默认资源
super(parent);
//为String[] configLocations属性赋值
setConfigLocations(configLocations);
if (refresh) {
//此方法从AbstractApplicationContext继承而来,它代表着一个容器的正式启动;
refresh();
}
}
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//启动前的准备工作,比如设置启动标识,记录启动时间等
prepareRefresh();
//得到一个BeanFactory,我们接下来重点分析怎么是创建bean工厂的
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//对bean工厂做些通用配置,使其符合当前上下文要求
prepareBeanFactory(beanFactory);
try {
// 允许让子类覆盖此方法有机会对bean工厂做些特殊配置
postProcessBeanFactory(beanFactory);
// 回调bean工厂后处理器,比如BeanDefinitionRegistryPostProcessor以及BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
// 注册bean后处理器,也就是实现了BeanPostProcessor接口的类
registerBeanPostProcessors(beanFactory);
//初始化消息资源,也就是对国际化的支持,默认使用DelegatingMessageSource,当然,我们也可以自己配置一个名叫messageSource的bean
initMessageSource();
// 初始化Spring的事件广播功能,默认采用SimpleApplicationEventMulticaster类实现,我们可以自己配置一个名叫applicationEventMulticaster的bean来实现
initApplicationEventMulticaster();
// 允许子类覆盖,在其它上下文做些初始化工作,比如WEB上下文,这个到解析SpringMVC时再做详细解析
onRefresh();
// 注册上下文事件监听器,也就是实现了ApplicationListener接口的Bean
registerListeners();
// 如果bean设置了lazy-init为false,那么它会在这里而被初始化,所谓初始化就是创建一个bean的实例,先前所有工作都只是创建好了一系列BeanDefinition而已,具体初始化流程这个后面再解析
finishBeanFactoryInitialization(beanFactory);
// 上下文构建完毕,发布事件,使得监听上下文构建过程的类得到回调
finishRefresh();
}
}
}
我们看到在refresh方法中有着众多方法调用,有些方法允许子类覆盖,使其功能得到扩展,这就是设计模式中典型的模板方法模式,后面的一些方法我们先不去关心,那些都比较简单后面再讲,现在我们先重点关注下BeanFactory的创建过程;
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//这是个抽象方法,具体创建bean工厂的过程交给子类来做
refreshBeanFactory();
//上述方法完成后,就可以正常拿到一个BeanFactory并返回了
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
//在AbstractRefreshableApplicationContext类中被实现
protected final void refreshBeanFactory() throws BeansException {
//如果当前上下文中存在了beanFactory,则销毁其内所有的bean以及bean工厂
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//看到没有,就像我们最开始那四行代码一样,Spring内部也是创建一个DefaultListableBeanFactory!
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
//载入bean定义,接下来我们进入这个方法看看
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
BeanFactory创建好后,它就准备去载入Bean定义了,怎么载入呢?起码它需要先定位到资源文件吧,接下来就去看它是怎么拿到Resource的;
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// 创建一个基于XML的bean定义读取器,就像我们最开始那四行代码,它内部也是创建一个XmlBeanDefinitionReader类!
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//配置好读取器的一些必要依赖对象
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
//允许子类覆盖该方法,用来做些特殊配置使其可以根据自己的需要来读取xml资源
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
//拿不到Resource,因为我们在创建ClassPathXmlApplicationContext时给的构造参数是一个字符串路径
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
//经过几个重载方法,最终进入到这里
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
//拿到资源载入器,也就是ClassPathXmlApplicationContext类,因为在上面有这么一行代码对其进行了配置
//beanDefinitionReader.setResourceLoader(this);
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//拿到资源集合,这里只会拿到一条数据,也就是我们的配置文件testSpringIOC.xml转换成的Resource
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//继续调用重载方法
int loadCount = loadBeanDefinitions(resources);
if (actualResources != null) {
for (Resource resource : resources) {
actualResources.add(resource);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
}
return loadCount;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
else {
Resource resource = resourceLoader.getResource(location);
int loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}
//再经过几个重载方法,会进入XmlBeanDefinition的真正实现方法中,以上方法都是它的父类AbstractBeanDefinitionReader实现的
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
//创建一个EncodedResource对象,使用特定的字符集以及编码包装resource
return loadBeanDefinitions(new EncodedResource(resource));
}
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
//通过Resource拿到输入流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//接下来进入此方法
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//将流文件解析成org.w3c.dom的Document对象, 通过com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl这个类来进行实现,
//这个过程我们不去关心,感兴趣可以去学习下;拿到Document后,开始向BeanFactory中注册从doc中解析出来的beanDefinition
Document doc = doLoadDocument(inputSource, resource);
return registerBeanDefinitions(doc, resource);
}
...
}
Ok,到了这里,资源文件已经定位到且转换成了Resource类更是被进一步转换成了Document对象,拿到Document对象后,Spring开始对Document内的元素进行提取解析工作,这就进入到了资源文件的解析范畴了,这个过程稍微有点复杂,设计到各种元素和命名空间的不同解析操作, 我们下一篇文章就来具体分析这个过程!
最后,我们画一个时序图来帮助我们更好的理解资源文件的定位与载入过程;