IOC第一部分:xml文件的解析

我们在main函数中从一行代码开始分析:

ConfigurableListableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring.xml"));

大多数人可能会有疑问,现在加载XML文件不是通过:

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml"); spring应用上下文来加载和操作XML文档的吗?没错,在spring2.5版本的时候还没有spring应用上下文对象,这个是spring在版本spring3以后加了ApplicationContext 对象,这个对象包含了 XmlBeanFactory对象的所有功能,对其进行了扩展。我们先分析 XmlBeanFactory的解析流程。

1.1 配置文件的封装

Spring是通过ClassPathResource对象进行封装。ClassPathResource对象实现esource接口,Resource接口对象封装了所有Spring内部使用到的底层资源:FileURLClassPath等。它定义了三个判断当前 资源状态方法:存在性(exists)、可读性(isReadable)、是否处于打开状态(isOpen)。对于不同来源的资源文件都有对应的实现:文件(FileSystemResource)ClassPath资源(ClassPathResource)URL资源(UrlResource)、InputStream资源(InputStreamResource)等。有了Resource接口可以对资源文件进行统一的处理了。当Resoure完成了对配置文件的封装后配置文件的读取工作就全权交给XmlBeanDefineReader来处理了。

new ClassPathResource("spring.xml") 来完成资源文件的封装.通过XmlBeanFactory的构造函数来完成数据的加载:

public XmlBeanFactory(Resource resource) throws BeansException {

this(resource, null);

}

 

/**

 * Create a new XmlBeanFactory with the given input stream,

 * which must be parsable using DOM.

 * @param resource XML resource to load bean definitions from

 * @param parentBeanFactory parent bean factory

 * @throws BeansException in case of loading or parsing errors

 */

public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {

super(parentBeanFactory);

this.reader.loadBeanDefinitions(resource);

}

this.reader.loadBeanDefinitions(resource)才是加载资源文件的最终实现。Reader指的就是XmlBeanDefineReader。

猜你喜欢

转载自www.cnblogs.com/histlyb/p/8975603.html