spring——xml配置文件的读取
spring xml资源文件读取主要涉及以下几个类关系如图1:
ResourceLoader:定义资源加载器,主要功能是根据给定的资源文件地址返回对应的Resource(Resource 是对资源的封装)
BeanDefinitionReader:主要定义资源文件读取并转换为BeanDefinition的各个功能
EnvironmentCapable:定义获取Environment的方法
DocumentLoader:定义从资源文件加载到转换为Document的功能
AbstractBeanDefinitionReader:对EnvironmentCapable,BeanDefinitionReader类定义的功能进行实现
BeanDefinitionDocumentReader:定义读取Document并注册BeanDefinition功能
BeanDefinitionParserDelegate:定义解析Element的方法
整个xml配置文件读取的大致流程如下:
1.通过继承AbstractBeanDefinitionReader 中的方法,使用ResourLoader将指定路径下的资源文件转换为对应的Resource文件。
2.通过DocumemtLoader对Resource封装的资源文件进行转换,将Resource文件转换为Document文件。
3.通过实现接口BeanDefinitionDocumentReader的DefaultBeanDefinitionDocumentReader类对Document进行解析,并使用BeanDefinitionParserDelegate对Element进行解析。
源码解析:
beanFactoryTest.xml 文件 + 测试类BeanFactoryTest.java代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="myTestBean" class="com.day1.MyTestBean"/>
</beans>
public class BeanFactoryTest {
@Test
public void testSimpleLoad(){
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));
MyTestBean myTestBean = (MyTestBean) beanFactory.getBean("myTestBean");
assertEquals("testStr",myTestBean.getTestStr());
}
}</