JDK 提供的访问资源的类(java.net.URL 和 File)不能满足各种底层资源的访问需求,比如缺少从类路径或 Web 容器的上下文中获取资源的操作类。因此,Spring 设计了一个 Resource 接口,为应用提供了更强的访问底层资源的能力。
资源接口 Resource
|
|
|
|
Resource 接口的主要方法:
- getInputStream():返回资源对应的输入流。
- exists():资源是否存在。
- isOpen():资源是否打开。
- getDescription():返回对资源的描述。
- getURL():如果底层资源可以表示成URL,则返回对应的 URL 对象。
- getFile():如果底层资源对应一个文件,则返回对应的 File 对象。
Resource 的具体实现类
- UrlResource:Url 封装了 java.net.URL,它使用户能够访问任何可以通过 URL 表示的资源,如文件系统的资源、HTTP 资源、FTP 资源等。
- ClassPathResource:类路径下的资源,资源以相对于类路径的方式表示。
- FileSystemResource:文件系统资源,资源以文件系统路径的方式表示。
- ServletContextResource:为访问 Web 容器上下文中的资源而设计的类,负责以相对于 Web 应用根目录的路径加载资源,它支持以流和 URL 的方式访问,在 WAR 解包的情况下,也可以通过 File 的方式访问,该类还可以直接从 JAR 包中访问资源。
- InputStreamResource:以输入流返回表示的资源。
- ByteArrayResource:二进制数组表示的资源,二进制数组资源可以在内存中通过程序构造。
示例:
资源地址表达式
Spring 提供了强大的加载资源的机制,不但能够通过 classpath:
、file:
等资源地址前缀识别不同的资源类型,还支持 Ant 风格带通配符的资源地址。
地址前缀 | 示例 | 对应资源类型 |
---|---|---|
classpath: | classpath:com/myapp/config.xml | 从类路径中加载资源,资源文件可以在标准的文件系统中,也可以在 jar 或 zip 的类包中 |
file: | file://data/config.xml | 使用 UrlResource 从文件系统目录中装载资源,可采用绝对或相对路径 |
http:// | http://myserver/logo.png | 使用 UrlResource 从 Web 服务器中装载资源 |
ftp:// | ftp://myserver/my.txt | 使用 UrlResource 从 FTP 服务器中装载资源 |
没有前缀 | /data/config.xml | 根据 ApplicationContext 具体实现类采用对应的类型的 Resource |
Ant 风格资源地址支持 3 种匹配符:
?
:匹配文件名中的一个字符*
:匹配文件名中任意个字符**
:匹配多层路径
示例:
classpath:com/t?st.xml
:匹配 com 类路径下 com/test.xml,com/tast.xml 或者 com/tdst.xmlfile:D:/conf/*.xml
:匹配文件系统 D:/conf 目录下所有以 xml 为后缀的文件classpath:com/**/test.xml
:匹配 com 类路径下(当前目录及其子孙目录)的 test.xml 文件