Spring Resource框架体系介绍

Resource介绍

在使用spring做为容器进行项目开发中会有不少的配置文件,这些配置文件都是经过Spring的Resource接口来实现加载,可是,Resource对于全部低级资源的访问都不够充分。例如,没有标准化的URL实现可用于访问须要从类路径或相对于ServletContext获取的资源。(更多关于ServletContext的理解,请访问https://www.cnblogs.com/cxuanBlog/p/10927813.html)虽然能够为专用的URL前缀注册新的处理程序(相似于http :)这样的前缀的现有处理程序,但这一般很是复杂,而且URL接口仍然缺乏一些理想的功能,例如检查存在的方法被指向的资源。html

JavaDoc解释

从实际类型的底层资源(例如文件或类路径资源)中抽象出来的资源描述符的接口。java

Resource接口方法

Spring的Resource接口旨在成为一个更有能力的接口,用于抽象对低级资源的访问。如下清单显示了Resource接口定义git

public interface Resource extends InputStreamSource {
 
  boolean exists();
  
  default boolean isReadable() {
        return true;
    }
  
  default boolean isOpen() {
        return false;
    }
  
  default boolean isFile() {
        return false;
    }
  
  URL getURL() throws IOException;
  
  URI getURI() throws IOException;
  
  File getFile() throws IOException;
  
  default ReadableByteChannel readableChannel() throws IOException {
        return Channels.newChannel(getInputStream());
    }
  
  long contentLength() throws IOException;
  
  long lastModified() throws IOException;
  
  Resource createRelative(String relativePath) throws IOException;
  
    String getFilename();
  
  String getDescription();
}

Resource接口继承了InputStreamSource接口,提供了不少InputStreamSource所没有的方法github

下面来看一下InputStreamSource接口,只有一个方法web

public interface InputStreamSource {

    InputStream getInputStream() throws IOException;

}

其中一些大部分重要的接口是:spring

  • getInputStream(): 找到并打开资源,返回一个InputStream以从资源中读取。预计每次调用都会返回一个新的InputStream(),调用者有责任关闭每一个流
  • exists(): 返回一个布尔值,代表某个资源是否以物理形式存在
  • isOpen: 返回一个布尔值,指示此资源是否具备开放流的句柄。若是为true,InputStream就不可以屡次读取,只可以读取一次而且及时关闭以免内存泄漏。对于全部常规资源实现,返回false,可是InputStreamResource除外。
  • getDescription(): 返回资源的描述,用来输出错误的日志。这一般是彻底限定的文件名或资源的实际URL。

其余方法:数据库

  • isReadable(): 代表资源的目录读取是否经过getInputStream()进行读取。
  • isFile(): 代表这个资源是否表明了一个文件系统的文件。
  • getURL(): 返回一个URL句柄,若是资源不可以被解析为URL,将抛出IOException
  • getURI(): 返回一个资源的URI句柄
  • getFile(): 返回某个文件,若是资源不可以被解析称为绝对路径,将会抛出FileNotFoundException
  • lastModified(): 资源最后一次修改的时间戳
  • createRelative(): 建立此资源的相关资源
  • getFilename(): 资源的文件名是什么 例如:最后一部分的文件名 myfile.txt

Resource的实现类

Resource 接口是 Spring 资源访问策略的抽象,它自己并不提供任何资源访问实现,具体的资源访问由该接口的实现类完成——每一个实现类表明一种资源访问策略。数组

基础类介绍

Resource通常包括这些实现类:UrlResource、ClassPathResource、FileSystemResource、ServletContextResource、InputStreamResource、ByteArrayResource网络

使用UrlResource访问网络资源

访问网络资源的实现类。Resource的一个实现类用来定位URL中的资源。它支持URL的绝对路径,用来做为file: 端口的一个资源,建立一个maven项目,配置Spring依赖(再也不赘述)和dom4j 的依赖,并在根目录下建立一个books.xml。app

代码表示:

public class UrlResourceTest {

    public static void loadAndReadUrlResource(String path) throws Exception{
        // 建立一个 Resource 对象,指定从文件系统里读取资源,相对路径
        UrlResource resource = new UrlResource(path);
        // 绝对路径
//        UrlResource resource = new UrlResource("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        // 获取文件名
        System.out.println("resource.getFileName = " + resource.getFilename());
        // 获取文件描述
        System.out.println("resource.getDescription = "+ resource.getDescription());
        SAXReader reader = new SAXReader();
        System.out.println(resource.getFile());
        Document document = reader.read("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        Element parent = document.getRootElement();
        List<Element> elements = parent.elements();
        for(Element element : elements){
            // 获取name,description,price
            System.out.println(element.getName() + " = " +element.getText());
        }
    }


    public static void main(String[] args) throws Exception {
        loadAndReadUrlResource("file:books.xml");
    }

}

上面程序使用UrlResource来访问网络资源,也能够经过file 前缀访问本地资源,上述代码就是这样作的。若是要访问网络资源,能够有两种形式

  • http:-该前缀用于访问基于 HTTP 协议的网络资源。
  • ftp:-该前缀用于访问基于 FTP 协议的网络资源。

使用ClassPathResource 访问类加载路径下的资源

ClassPathResource 用来访问类加载路径下的资源,相对于其余的 Resource 实现类,其主要优点是方便访问类加载路径里的资源,尤为对于 Web 应用,ClassPathResource 可自动搜索位于 WEB-INF/classes 下的资源文件,无须使用绝对路径访问。

public class ClassPathResourceTest {

    public static void loadAndReadUrlResource(String path) throws Exception{
        // 建立一个 Resource 对象,指定从文件系统里读取资源,相对路径
        ClassPathResource resource = new ClassPathResource(path);
        // 绝对路径
//        UrlResource resource = new UrlResource("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        // 获取文件名
        System.out.println("resource.getFileName = " + resource.getFilename());
        // 获取文件描述
        System.out.println("resource.getDescription = "+ resource.getDescription());
        SAXReader reader = new SAXReader();
        System.out.println(resource.getPath());
        Document document = reader.read("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        Element parent = document.getRootElement();
        List<Element> elements = parent.elements();
        for(Element element : elements){
            // 获取name,description,price
            System.out.println(element.getName() + " = " +element.getText());
        }
    }


    public static void main(String[] args) throws Exception {
        loadAndReadUrlResource("books.xml");
    }
}

除了以上新建方式的不一样,其余代码和上述代码一致,这就是 Spring 资源访问的优点:Spring 的资源访问消除了底层资源访问的差别,容许程序以一致的方式来访问不一样的底层资源。

使用FileSystemResource 访问文件资源系统

Spring 提供的 FileSystemResource 类用于访问文件系统资源,使用 FileSystemResource 来访问文件系统资源并无太大的优点,由于 Java 提供的 File 类也可用于访问文件系统资源。

固然使用 FileSystemResource 也可消除底层资源访问的差别,程序经过统一的 Resource API 来进行资源访问。下面程序是使用 FileSystemResource 来访问文件系统资源的示例程序。

public class FileSystemResourceTest {

    public static void loadAndReadUrlResource(String path) throws Exception{
        // 建立一个 Resource 对象,指定从文件系统里读取资源,相对路径
        FileSystemResource resource = new FileSystemResource(path);
        // 绝对路径
//        UrlResource resource = new UrlResource("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        // 获取文件名
        System.out.println("resource.getFileName = " + resource.getFilename());
        // 获取文件描述
        System.out.println("resource.getDescription = "+ resource.getDescription());
        SAXReader reader = new SAXReader();
        System.out.println(resource.getFile());
        Document document = reader.read("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        Element parent = document.getRootElement();
        List<Element> elements = parent.elements();
        for(Element element : elements){
            // 获取name,description,price
            System.out.println(element.getName() + " = " +element.getText());
        }
    }


    public static void main(String[] args) throws Exception {
        loadAndReadUrlResource("books.xml");
    }
}

FileSystemResource 实例可以使用 FileSystemResource 构造器显式地建立。但更多的时候它都是隐式建立的,执行 Spring 的某个方法时,该方法接受一个表明资源路径的字符串参数,当 Spring 识别该字符串参数中包含 file: 前缀后,系统将会自动建立 FileSystemResource 对象。

ServletContextResource

这是ServletContext资源的Resource实现,它解释相关Web应用程序根目录中的相对路径。

它始终支持流(stream)访问和URL访问,但只有在扩展Web应用程序存档且资源实际位于文件系统上时才容许java.io.File访问。不管它是在文件系统上扩展仍是直接从JAR或其余地方(如数据库)访问,实际上都依赖于Servlet容器。

InputStreamResource

InputStreamResource 是给定的输入流(InputStream)的Resource实现。它的使用场景在没有特定的资源实现的时候使用(感受和@Component 的适用场景很类似)。

与其余Resource实现相比,这是已打开资源的描述符。 所以,它的isOpen()方法返回true。若是须要将资源描述符保留在某处或者须要屡次读取流,请不要使用它。

ByteArrayResource

字节数组的Resource实现类。经过给定的数组建立了一个ByteArrayInputStream

它对于从任何给定的字节数组加载内容很是有用,而无需求助于单次使用的InputStreamResource。

Resource类图与策略模式

上述Resource实现类与Resource顶级接口之间的关系能够用下面的UML关系模型来表示

策略模式

上述流程图是否是对同一行为的不一样实现方式,这种实现方式像极了策略模式?具体关于策略模式的文章,请参考

https://www.runoob.com/design-pattern/strategy-pattern.html

ResourceLoader 接口

ResourceLoader接口旨在由能够返回(即加载)Resource实例的对象实现,该接口实现类的实例将得到一个 ResourceLoader 的引用。下面是ResourceLoader的定义

public interface ResourceLoader {
        
    //该接口仅包含这个方法,该方法用于返回一个 Resource 实例。ApplicationContext 的实现类都实现       ResourceLoader 接口,所以 ApplicationContext 可用于直接获取 Resource 实例
    Resource getResource(String location);

}

全部的应用程序上下文都实现了ResourceLoader接口。所以,全部的应用程序上下文均可能会获取Resource实例。

在特定应用程序上下文上调用getResource()而且指定的位置路径没有特定前缀时,将返回适合该特定应用程序上下文的Resource类型。 例如,假设针对ClassPathXmlApplicationContext实例执行了如下代码:

Resource template = ctx.getResource("some/resource/path/myTemplate.txt");

你暂时不知道具体的上下文资源类型是什么,假设指定的是ClassPathXmlApplicationContext,上述代码就会返回ClassPathResource,若是执行上面相同的方法的是FileSystemXmlApplicationContext,上述代码就会返回的是FileSystemResource,对于web系统来讲,若是上下文容器时候WebApplicationContext,那么返回的将是ServletContextResource,它一样会为每一个上下文返回适当的对象。所以,您能够以适合特定应用程序上下文的方式加载资源。

另外一方面,你可能强制使用ClassPathResource,忽略应用程序的上下文类型,经过添加特定的前缀classpath:,如下示例说明了这一点。

Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");

一样的,你可以强制使用UrlResource经过使用特定的前缀:java.net.URL。下述两个例子分别表示使用httpfile前缀。

Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");

Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");

下列表格对资源类型和前缀进行更好的汇总:

Prefix Example Explanation
classpath: classpath:com/myapp/config.xml 从类路径加载
file: file:///data/config.xml 从文件系统加载做为URL,查阅FileSystemResource
http: https://myserver/logo.png 加载做为URL
(none) /data/config.xml 依赖于ApplicationContext

ResourceLoaderAware 接口

这个ResourceLoaderAware接口是一个特殊的回调接口,用于标识但愿随ResourceLoader引用提供的组件,下面是ResourceLoaderAware 接口的定义

public interface ResourceLoaderAware extends Aware {

    void setResourceLoader(ResourceLoader resourceLoader);
}

ResourceLoaderAware 接口用于指定该接口的实现类必须持有一个 ResourceLoader 实例。

相似于BeanNameAwareBeanFactoryAware接口,ResourceLoaderAware接口也提供了一个setResourceLoader()方法,该方法由Spring容器负责,Spring 容器会将一个 ResourceLoader 对象做为该方法的参数传入。

固然了,一个 bean 若想加载指定路径下的资源,除了刚才提到的实现 ResourcesLoaderAware 接口以外(将 ApplicationContext 做为一个 ResourceLoader 对象注入),bean 也能够实现 ApplicationContextAware 接口,这样能够直接使用应用上下文来加载资源。但总的来讲,在需求知足都知足的状况下,最好是使用的专用 ResourceLoader 接口,由于这样代码只会与接口耦合,而不会与整个 spring ApplicationContext 耦合。与 ResourceLoader 接口耦合,抛开 spring 来看,就是提供了一个加载资源的工具类接口。因为ApplicationContext也是一个ResourceLoader,所以bean还能够实现ApplicationContextAware接口并直接使用提供的应用程序上下文来加载资源。可是,一般状况下,若是有须要的话最好仍是使用特定的ResourceLoader接口。

在应用程序的组件中,除了实现 ResourceLoaderAware 接口,也可采起另一种替代方案——依赖于 ResourceLoader 的自动装配。传统的构造函数注入和byType自动装配模式(如自动装配协做者中所述)可以分别为构造函数参数或setter方法参数提供ResourceLoader。若为了得到更大的灵活性(包括属性注入的能力和多参方法),能够考虑使用基于注解的新注入方式。使用注解 @Autowiring 标记 ResourceLoader 变量,即可将其注入到成员属性、构造参数或方法参数中。

使用Resource做为属性

前面介绍了 Spring 提供的资源访问策略,但这些依赖访问策略要么须要使用 Resource 实现类,要么须要使用 ApplicationContext 来获取资源。实际上,当应用程序中的 Bean 实例须要访问资源时,Spring 有更好的解决方法:直接利用依赖注入。

从这个意义上来看,Spring 框架不只充分利用了策略模式来简化资源访问,并且还将策略模式和 IoC 进行充分地结合,最大程度地简化了 Spring 资源访问。

概括起来,若是 Bean 实例须要访问资源,有以下两种解决方案:

  • 代码中获取 Resource 实例。
  • 使用依赖注入。

对于第一种方式的资源访问,当程序获取 Resource 实例时,总须要提供 Resource 所在的位置,无论经过 FileSystemResource 建立实例,仍是经过 ClassPathResource 建立实例,或者经过 ApplicationContext 的 getResource() 方法获取实例,都须要提供资源位置。这意味着:资源所在的物理位置将被耦合到代码中,若是资源位置发生改变,则必须改写程序。所以,一般建议采用第二种方法,让 Spring 为 Bean 实例依赖注入资源。

如下示例说明了这一点(可使用set方法注入):

public class TestBean {

    private Resource resource;

    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public void parse() throws Exception {
        // 获取文件名
        System.out.println("resource.getFileName = " + resource.getFilename());
        // 获取文件描述
        System.out.println("resource.getDescription = "+ resource.getDescription());
        SAXReader reader = new SAXReader();
        Document document = reader.read("file:///Users/mr.l/test/CXuan-Spring/CXuan-Spring-Resource/books.xml");
        Element parent = document.getRootElement();
        List<Element> elements = parent.elements();
        for(Element element : elements){
            // 获取name,description,price
            System.out.println(element.getName() + " = " +element.getText());
        }
    }

    public static void main(String[] args) throws Exception {
        TestBean testBean = new TestBean();
        testBean.setResource(new ClassPathResource("beans.xml"));
        testBean.parse();
    }
}

上面配置文件配置了资源的位置,并使用了 classpath: 前缀,这指明让 Spring 从类加载路径里加载 book.xml 文件。与前面相似的是,此处的前缀也可采用 http:、ftp: 等,这些前缀将强制 Spring 采用怎样的资源访问策略(也就是指定具体使用哪一个 Resource 实现类);若是不采用任何前缀,则 Spring 将采用与该 ApplicationContext 相同的资源访问策略来访问资源。

<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:///some/resource/path/myTemplate.txt"/>

应用程序上下文和资源路径

本节介绍如何使用资源建立应用程序上下文,包括使用XML的快捷方式,如何使用通配符以及其余详细信息。

构造应用程序上下文

应用程序上下文构造函数(对于特定的应用程序上下文类型)一般将字符串或字符串数组做为资源的位置路径,例如构成上下文定义的XML文件。

当这样的位置路径没有前缀时,从该路径构建并用于加载bean定义的特定资源类型取决于而且适合于特定的应用程序上下文。 例如,请考虑如下示例,该示例建立ClassPathXmlApplicationContext:

ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");

bean 定义从类路径中加载,由于ClassPathResource被使用了,然而,考虑如下例子,建立了一个FileSystemXmlApplicationContext:

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

如今bean的定义信息会从文件系统中加载,请注意,在位置路径上使用特殊类路径前缀或标准URL前缀会覆盖为加载定义而建立的默认资源类型。 请考虑如下示例:

ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");

建立 Spring 容器时,系统将从类加载路径来搜索 appContext.xml;但使用 ApplicationContext 来访问资源时,依然采用的是 FileSystemResource 实现类,这与 FileSystemXmlApplicationContext 的访问策略是一致的。这代表:经过 classpath: 前缀指定资源访问策略仅仅对当次访问有效,程序后面进行资源访问时,仍是会根据 AppliactionContext 的实现类来选择对应的资源访问策略。

应用程序上下文路径中的通配符

上下文构造资源的路径多是一些简单路径,可是对于每个映射来讲,不可能只有简单路径,也会有特殊复杂的路径出现,这就须要使用到路径通配符(ant-style)。

ant-style示例

/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml

classpath* 和 classpath的区别:

classpath: 当使用 classpath :时前缀来指定 XML 配置文件时,系统将搜索类加载路径,找出全部与文件名的文件,分别装载文件中的配置定义,最后合并成一个 ApplicationContext。

public static void main(String[] args) throws Exception { 
  // 使用 classpath* 装载多份配置文件输出 ApplicationContext 实例。
  ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:bean.xml");
  System.out.println(ctx); 
}

若是不是采用 classpath*: 前缀,而是改成使用 classpath: 前缀,Spring 只加载第一份符合条件的 XML 文件,例如以下代码

ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:bean.xml");

当使用 classpath: 前缀时,系统经过类加载路径搜索 bean.xml 文件,若是找到文件名匹配的文件,系统当即中止搜索,装载该文件,即便有多份文件名匹配的文件,系统只装载第一份文件。

路径匹配

另外,还有一种能够一次性装载多份配置文件的方式:指定配置文件时指定使用通配符,例如以下代码:

ApplicationContext ctx = new ClassPathXmlApplicationContext("bean*.xml");

除此以外,Spring 甚至容许将 classpath*: 前缀和通配符结合使用,以下语句也是合法的:

ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:bean*.xml");

file 前缀的用法

相对路径的写法:

ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");

绝对路径的写法:

ApplicationContext ctx = new FileSystemXmlApplicationContext("/bean.xml");

若是程序中须要访问绝对路径,则不要直接使用 FileSystemResource 或 FileSystemXmlApplicationContext 来指定绝对路径。建议强制使用 file: 前缀来区分相对路径和绝对路径,例如以下两行代码

ApplicationContext ctx = new FileSystemXmlApplicationContext("file:bean.xml"); 
ApplicationContext ctx = new FileSystemXmlApplicationContext("file:/bean.xml");

文章参考:

Spring官方文档: https://docs.spring.io/spring/docs/5.1.7.RELEASE/spring-framework-reference/core.html#resources

IBM使用手册:https://www.ibm.com/developerworks/cn/java/j-lo-spring-resource/index.html

相关文章
相关标签/搜索