ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
Spring加载xml数据的切入点是通过ClassPathXmlApplicationContext类进行切入的。该类是面向xml文件。类似的spring还提供了面向注解的解析类AnnotationConfigApplicationContext等。
进入
new ClassPathXmlApplicationContext("spring-config.xml");
之后代码如下:
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
Spring容器的加载、xml文件的解析器以及单例、非懒加载的类等都是由refresh()方法完成。Refresh代码如下所示:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备刷新环境列入对系统属性或者环境变量进行准备及验证
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
/* 调用子类AbstractRefreshableApplicationContext 刷新DefaultListableBeanFactory工厂
* 功能描述 1、创建核心组件ConfigurableListableBeanFactory
* 2、获取xml、注解等方式的配置,将其转换为原数据放入ConfigurableListableBeanFactory中
* 3、xml读取
*/
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
/* 创建单例或者非懒加载实例*/
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset ‘active‘ flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring‘s core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
如代码所示xml数据的读取主要是在obtainFreshBeanFactory()方法中进行处理的。而AbstractApplicationContext类中并没有对obtainFreshBeanFactory()方法做具体的实现,而是将其交由子类AbstractRefreshableApplicationContext去实现
Xml的读取主要处理2个问题
1、准备容器,用于存储解析后的数据
2、准备documentReader,用于解析spring配置文件
代码如下:
@Override
protected final void refreshBeanFactory() throws BeansException {
/**
* DefaultListableBeanFactory被实例化至少一次时将销毁spring创建的对象,并且关闭DefaultListableBeanFactory实例
*/
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();//创建spring的核心组件
//为了序列化指定id
beanFactory.setSerializationId(getId());
//定制beanFactory,设置相关属性。
customizeBeanFactory(beanFactory);
//初始化xml读取器、读取原数据切入点 交由子类处理
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
该方法主要完成以下几个工作:
1、校验DefaultListableBeanFactory被实例化至少一次时将销毁spring创建的对象,并且关闭DefaultListableBeanFactory实例
2、创建spring的核心组件DefaultListableBeanFactory的具体实例并设置相应参数,也就是beanFactory。
3、初始化xml读取器、读取xml数据切入点 交由子类处理。
4、将beanFactory设定为全局变量。
AbstractRefreshableApplicationContext并没有对loadBeanDefinitions()方法进行具体的实现,而是将其交由子类去做处理,这样做的好处是针对不同的spring配置方式采用不同的解析方式进行解析(策略模式)。
Ps:此处只针对xml文件的配置(AbstractXmlApplicationContext)解析进行说明
上面部分代码完成了对beanFactory的定制,并且对xml文件的解析做了切入loadBeanDefinitions();
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
/*依据beanFactory创建新的XmlBeanDefinitionReader */
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context‘s
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
以上代码完成以下功能
1、为特定的beanFactory准备相应的beanDefinitionReader 并完成相应设置
2、切入loadBeanDefinitions();
Xml文件的解析是交由专门的解析类AbstractBeanDefinitionReader进行处理。
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);
}
}
Ps:读者可参考此图