XmlBeanFactory的解析
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));
上面代码的执行逻辑,如下:
title XmlBeanFactory 初始化时序图 bf(BeanFactoryTest)->+res(ClassPathResource):1. new ClassPathResource("beanFactory.xml") res(ClassPathResource)-->-bf(BeanFactoryTest):2. resource:Resource bf(BeanFactoryTest)->+xF(XmlBeanFactory):3. new XmlBeanFactory(resource) xF(XmlBeanFactory)->+reader(XMLBeanDefinitionReader):3.1 loadBeanDefinitions(resource) reader(XMLBeanDefinitionReader)-->-xF(XmlBeanFactory):3.2 loadBeanDefintionNum:int xF(XmlBeanFactory)-->-bf(BeanFactoryTest):4. xF:BeanFactory
通过时序图我们可以一目了然的看到整个逻辑的处理顺序。在测试的例子中首先调用ClassPathResource的构造函数来构造Resource资源文件的实例对象,这样后续的资源处理中我们就可以用Resource提供的各种服务来操作了。
配置文件的封装
在JAVA中,将不同的资源抽象成URL,通过注册不同的handle(URLStreamHandler)来处理不同来源的资源读取逻辑,一般handle的类型使用不同的前缀(协议,Protocol)来识别,然而URL没有默认定义相对的ClassPath或ServletContext等资源的handle,我们需要了解URL的实现机制来注册自已的URLStreamHandler来解析特定的URL前缀。因而Spring对其内部使用的资源实现了自已的抽象结构:Resource接口来封装底层资源。
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
public interface Resource extends InputStreamSource {
boolean exists(); //存在性
boolean isReadable() ; //可读性
boolean isOpen(); //是否处于打开状态
default boolean isFile(); //Determine whether this resource represents a file in a file system.
URL getURL() throws IOException; //Return a URL handle for this resource.
URI getURI() throws IOException; //Return a URI handle for this resource.
File getFile() throws IOException; //Return a File handle for this resource.
default ReadableByteChannel readableChannel() throws IOException ; //Return a {@link ReadableByteChannel}.
long contentLength() throws IOException; //Determine the content length for this resource.
long lastModified() throws IOException; //Determine the last-modified timestamp for this resource.
Resource createRelative(String relativePath) throws IOException; //Create a resource relative to this resource.
@Nullable
String getFilename(); //Determine a filename for this resource, i.e. typically the last
String getDescription(); //用于在错误处理中的打印信息
}
资源文件处理的相关类图