【转】https://blog.csdn.net/hbtj_1216/article/details/85487787

参考:官方文档

1 简介

Java标准库中的java.net.URL类和标准处理器对于处理低层的资源没有提供很好的功能。例如,并没有提供一个URL的实现能够从classpath或者ServletContext中读取资源等等。因此,在Spring中提供了这样一个Resource接口,能够更加方便的读取各种资源。

2 Resource接口

Spring提供的Resource接口,是对第低层资源访问进行的一个抽象,提供能方便的使用。

下面是org.springframework.core.io.Resource接口的定义:

public interface Resource extends InputStreamSource {

	/**
* 判断资源在物理上是否存在
*/
boolean exists(); /**
* 表明该资源中的非空内容是否可以通过getInputStream()读取
*/
default boolean isReadable() {
return exists();
} /**
* 表明该资源是否被一个打开的stream处理
*/
default boolean isOpen() {
return false;
} /**
* 判断该资源是否代表文件系统中的一个文件
*/
default boolean isFile() {
return false;
} /**
* 返回该资源的URL
*/
URL getURL() throws IOException; /**
* 返回该资源的URI
*/
URI getURI() throws IOException; /**
* 返回该资源对应的File
*/
File getFile() throws IOException; /**
* 返回一个ReadableByteChannel(可读的字节流通道)
*/
default ReadableByteChannel readableChannel() throws IOException {
return Channels.newChannel(getInputStream());
} /**
* 返回资源中内容的长度
*/
long contentLength() throws IOException; /**
* 返回该资源的最后修改时间
*/
long lastModified() throws IOException; /**
* 创建一个和该资源相关的资源
*/
Resource createRelative(String relativePath) throws IOException; /**
* 返回文件名
*/
@Nullable
String getFilename(); /**
* 返回资源的描述
*/
String getDescription(); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

Resource接口继承的InputStreamSource接口中海油一个非常重要的方法:

public interface InputStreamSource {

	/**
* 找到并打开资源,返回读取资源内容的InputStream. 每次调用返回一个新的InputStream.
*/
InputStream getInputStream() throws IOException; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3 Spring中内置的Resource接口的实现类

Spring中包含了如下几个Resource接口的实现类:

  • UrlResource:从URL获取资源。
  • ClassPathResource:从classpath获取资源。
  • FileSystemResource:从文件系统获取资源。
  • ServletContextResource:从servlet上下文获取资源。
  • InputStreamResource:从InputStream获取资源。
  • ByteArrayResource:从字节数组获取资源。

UrlResource

UrlResource是对java.net.URL的封装,可以被用来访问任何可以通过URL访问的资源对象,例如文件、HTTP目标对象、FTP目标对象等等。

每种类型的URL都有表示该类型资源的前缀。例如file:表示访问文件系统的URL;http:表示通过http协议访问;ftp:表示通过ftp协议访问。

ClassPathResource

ClassPathResource表示从classpath中获取资源。

FileSystemResource

FileSystemResource是对java.io.File和java.nio.file.Path的封装,代表从文件系统中读取文件。

ServletContextResource

ServletContextResource是为了方便你从ServletContext中获取资源而设计的,可以从相对于web应用程序的根目录中获取资源。

InputStreamResource

InputStreamResource是用来从给定的InputStream中获取资源的。

ByteArrayResource

ByteArrayResource用来从给定的字节数组中获取资源,它会创建一个ByteArrayInputStream。

4 ResourceLoader

ResourceLoader接口是用来加载资源的,它提供了一个getResource函数用来返回一个Resource对象。下面是它的定义:

public interface ResourceLoader {

	String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;

	Resource getResource(String location);

	@Nullable
ClassLoader getClassLoader();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

所有的应用程序上下文都实现了ResourceLoader接口,因此可以从应用程序上下文中获取Resource对象:

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

如果在调用getResource()的时候,指定的资源路径上没有给出前缀,那么Spring会根据context的类型返回一个合适类型的资源对象。例如,在ClassPathXmlApplicationContext对象上调用getResource()函数,则会返回一个ClassPathResource对象。

如果你指定了前缀,那么不管context是什么类型,都将返回前缀对应的资源类型,例如:

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

下表总结了资源路径对应的资源类型:

前缀 例子 说明
classpath: classpath:com/myapp/config.xml 从classpath加载资源。
file: file:///data/config.xml 从文件系统加载资源。
http: http://myserver/logo.png 使用http协议加载资源。
(none) /data/config.xml 根据context类型判断。

5 ResourceLoaderAware接口

ResourceLoaderAware是Spring提供的一个回调接口,用于注入ResourceLoader:

public interface ResourceLoaderAware extends Aware {

	void setResourceLoader(ResourceLoader resourceLoader);
}
  • 1
  • 2
  • 3
  • 4

如果一个类实现了ResourceLoaderAware接口并在Spring上下文中注册为一个bean,那么context会调用它的setResourceLoader()方法将context本身设置进去(因为所有的context都实现了ResourceLoader接口)。

下面是一个例子:

@Component
public class ResourceBean implements ResourceLoaderAware { private ResourceLoader resourceLoader; @Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
} public ResourceLoader getResourceLoader() {
return resourceLoader;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("test/resourceLoaderAware.xml");
ResourceBean resourceBean = ctx.getBean(ResourceBean.class);
ResourceLoader loader = resourceBean.getResourceLoader();
Assert.assertTrue(loader instanceof ApplicationContext);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上述方法采用实现ResourceLoaderAware接口的方式注入ResourceLoader,属于侵入式的方法。从Spring 2.5之后,可以直接通过@Autowired自动注入的方式注入ResourceLoader。

6 应用个上下文和资源路径

6.1 构造一个应用上下文

应用上下文的构造函数通常将资源的路径以一个字符串或者字符串数组传入。当路径没有前缀的时候,资源的类型依据上下文的类型构建。

下面的例子,通过资源的路径构造一个ClassPathXmlApplicationContext上下文对象:

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

下面的例子,根据资源路径构造一个FileSystemXmlApplicationContext上下文对象:

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

也可以通过路径前缀指定具体资源的类型。

6.2 资源路径支持通配符

可以通过*来表示一批资源文件:

/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml
  • 1
  • 2
  • 3
  • 4

6.3 classpath*:和classpath:

classpath*: 和classpath:的主要区别体现在:

  • classpath::只会在当前项目的WEB-INF/classes路径下查找文件。
  • classpath*::不只在当前羡慕的WEB-INF/classes路径下查找文件,还会到第三方jar文件的WEB-INF/classes查找文件。

6.4 FileSystemResource的路径问题

为了兼容,FileSystemXmlApplicationContext中的相对路径和绝对路径都将视为相对路径,相对于当前项目的工作目录。

下面两个是等价的:

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/context.xml");
  • 1
ApplicationContext ctx = new FileSystemXmlApplicationContext("/conf/context.xml");
  • 1

如果真的需要绝对路径,应该尽量使用UrlResource并通过file:前缀来指定:

// actual context type doesn't matter, the Resource will always be UrlResource
ctx.getResource("file:///some/resource/path/myTemplate.txt");
  • 1
  • 2
// force this FileSystemXmlApplicationContext to load its definition via a UrlResource
ApplicationContext ctx = new FileSystemXmlApplicationContext("file:///conf/context.xml");

Resource接口的更多相关文章

  1. 攻城狮在路上(贰) Spring(三)--- Spring 资源访问利器Resource接口

    Spring为了更好的满足各种底层资源的访问需求.设计了一个Resource接口,提供了更强的访问底层资源的能力.Spring框架使用Resource装载各种资源,包括配置文件资源.国际化属性文件资源 ...

  2. Resource接口,及资源

    Resource介绍 编码的时候,除了代码本身,我们还需要对外部的资源进行处理.例如:URL资源.URI资源.File资源.ClassPath相关资源.服务器相关资源(VFS等)等等. 而这些资源的处 ...

  3. spring-第十四篇之资源访问Resource接口

    1.Resource接口提供的主要方法 1>getInputStream():定位并打开资源,返回资源对应的输入流.每次调用都返回新的输入流.调用者必须负责关闭输入流. 2>isOpen( ...

  4. 通过Spring Resource接口获取资源

    目录 1       Resource简介 2       通过ResourceLoader获取资源 3       在bean中获取Resource的方式 1       Resource简介 在S ...

  5. Spring系列.Resource接口

    接口简介 JDK中提供了java.net.URL这个类来用于获取不同种类的资源(根据不同前缀的url可以获取不同种类的资源).但是URL这个类没有获取classpath和ServletContext下 ...

  6. Spring系列18:Resource接口及内置实现

    本文内容 Resource接口的定义 Resource接口的内置实现 ResourceLoader接口 ResourceLoaderAware 接口 Resource接口的定义 Java 的标准 ja ...

  7. Spring Resource接口获取资源

    1.1.1. Resource简介 在Spring内部实现机制,针对于资源文件(配置的xml文件)有一个统一的接口Resource. 1.1.1.1. 接口定义的方法 1.exists():判断资源文 ...

  8. Spring中Resource接口的前缀书写格式

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

  9. Bean利用Resource接口获取资源的几种方式

    Resources的类型 获取resource的方式(xml配置正常进行):

随机推荐

  1. 安卓微信overflow-x overflow-y引发的bug

    今天xgo文章图片页上线用微信扫页面发现一个bug,页面可以双击放大缩小. 找了半天原因,发现是图片描述设置了overflow-y引发的bug. 建议在微信场景里满屏显示不能滚动的页面里慎用overf ...

  2. Python3 IO编程之操作文件和目录

    如果我们要操作文件,目录,可以在命令行下面输入操作系统提供的各种命令来完成.比如ls,cp等命令 如果要在python程序中执行这些目录和文件的操作怎么办?其实操作系统提供的命令指示简单地调用了操作系 ...

  3. linux编程 新建一个进程的方法

    学习到一种,直接调用系统函数,在类的构造函数中直接启动一个线程,例如,某个类是用来监听串口的,可以直接在其构造函数中调用系统函数,开辟一个进程,在该进程对应的函数中不断while(1){....} h ...

  4. LeetCode 108. 将有序数组转换为二叉搜索树(Convert Sorted Array to Binary Search Tree) 14

    108. 将有序数组转换为二叉搜索树 108. Convert Sorted Array to Binary Search Tree 题目描述 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索 ...

  5. Djang简单使用

    用户访问内容 ​ 用户能够访问的所有的资源,都是程序猿提前暴露的,如果没有暴露,用户是不能进行访问的. diango重启的问题 ​ 当我们更改django中的代码的时候,django内部会检测到我们更 ...

  6. 1.IO的演进

      1.Java IO 演进之路 本文围绕着一下几个问题 1.Java 中 BIO.NIO.AIO 之间的区别及应用场景. 2.阻塞(Block)与非阻塞(Non-Block)区别. 3.同步(Syn ...

  7. (4)Spring Boot Web开发---静态资源

    文章目录 对静态资源的映射规则 模板引擎 Thymeleaf 使用 & 语法 使用之前将的快速创建项目的方法,勾选我们需要的场景,这里我需要 web --> web.sql --> ...

  8. django使用pyecharts(6)----django加入echarts_增量更新_定长_坐标轴定长

    六.Django 前后端分离_定时增量更新图表(坐标轴定长) 1.安装 djangorestframework linux pip3 install djangorestframework windo ...

  9. 第四章 函数之lambda 表达式和内置函数

    4.5 lambda 表达式 用于表示简单的函数. # 三元运算,为了解决简单的if else的情况,如:if 1 == 1:    a = 123else:    a = 456# 相当于a = 1 ...

  10. 【已解决】每次打开Excel时会同时打开一个空的Excel表格

    每次打开Excel时会同时打开一个空的Excel表格,情况如图. 官方解法如下,本人验证有效: 方法1, 请到以后路径中检查是否存在与空白文件夹同名字的Excel文件,删除它. C:\Users\\A ...