Spring定义了Resource接口用来对资源的访问,一般来说资源有两种形式,一种是URL的形式从外部链接加载,一种是File的形式从系统本身查找。

Spring的Resource提供了如下接口:

public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isOpen();

    URL getURL() throws IOException;

    File getFile() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();

}

Resource继承了InputStreamSource接口,下面是其定义:

public interface InputStreamSource {

    InputStream getInputStream() throws IOException;

}

内置Resource实现

Spring有如下几种内置资源实现:

  • UrlResource
  • ClassPathResource
  • FileSystemResource
  • ServletContextResource
  • InputStreamResource
  • ByteArrayResource

UrlResource

UrlResource封装了java.net.URL,可用于访问通常可通过url访问的任何对象,如文件、HTTP目标、FTP目标和其他对象。所有URL可以使用一个标准化前缀来表示一个URL类型。例如:

file:用于访问文件系统路径。

http:用于通过HTTP协议访问资源。

ftp:用于通过FTP访问资源。

ClassPathResource

表示从类路径加载资源。如果资源路径带上前缀ClassPath:,那么会隐式的解析为ClassPathResource。

注意,如果类资源文件是在文件系统中,则该资源实现会被解析为java.io.File, 如果是在Jar包中,则会使用java.net.URL来解析。

FileSystemResource

他是java.io.File和java.nio.file.Path的Resource实现,支持解析为File或者URL。

ServletContextResource

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

InputStreamResource

InputStreamResource 是InputStream 的Resource实现。只有在其他Resource实现不可用的时候才考虑使用它。

和其他的Resource实现相反,它是一个already-opened resource的描述器,所以isOpen()会返回true。 如果你想保存资源描述器或者多次读取一个stream, 那么不要使用它。

ByteArrayResource

是byte array的Resource实现, 它创建了ByteArrayInputStream。

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

ResourceLoader

ResourceLoader用来返回Resource实例,下面是其定义:

public interface ResourceLoader {

    Resource getResource(String location);

}

所有的 application contexts 都实现了ResourceLoader类。因此所有的application contexts 都可以用来获取Resource。

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

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

在ClassPathXmlApplicationContext中,这个方法返回ClassPathResource,如果在FileSystemXmlApplicationContext中,方法返回FileSystemResource。 在WebApplicationContext, 方法返回ServletContextResource。 他会返回和ApplicationContext相对应的Resource实现。

当然,你可以强制ClassPathResource使用,而不管ApplicationContext到底是什么。这样做你需要添加classpath:前缀。如下:

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

同样的,你可以强制使用UrlResource通过添加标准的java.net.URL前缀。

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

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

ResourceLoaderAware

ResourceLoaderAware接口是一个特殊的回调,表明该组件需要提供一个ResourceLoader的引用。 下面是ResourceLoaderAware的定义:

public interface ResourceLoaderAware {

    void setResourceLoader(ResourceLoader resourceLoader);
}

当一个类实现了ResourceLoaderAware并被部署到application context,那么整个类就被识别为ResourceLoaderAware。 application context会去调用setResourceLoader(ResourceLoader)方法,并将其自身作为参数传入(所有的Spring application contexts 都实现了ResourceLoader 接口)。

在应用程序组件中,你也可以使用自动装载ResourceLoader,来替代使用ResourceLoaderAware接口。可以使用传统的constructor或者byType的自动装载模式。或者使用注解的方式。

资源作为依赖

如果想将静态资源注入到Bean中,可以简单的将String路径转换为Resource对象。 如果Bean定义了一个Resource类型的template属性,那么下面就是一个很简单的资源配置的例子:

@Data
public class BeanA { private Resource template; }
    <bean id="myBean" class="com.flydean.beans.BeanA">
<property name="template" value="bean.properties"/>
</bean>

构造ClassPathXmlApplicationContext-快捷方式

ClassPathXmlApplicationContext提供了一个快捷方式来查找需要加载的资源路径。

只需提供一个字符串数组,该数组只包含XML文件本身的文件名(不包含前导路径信息),还提供一个类。然后,ClassPathXmlApplicationContext从提供的类中派生路径信息。

如下:

    public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"beanA.xml"}, BeanA.class);
}

下面是文件结构:

com/
flydean/
beans/
beanA.xml
BeanA.class

资源路径通配符

Ant-style Patterns

定义资源路径可以是用Ant-style的通配符,下面是 Ant-style patterns 的路径例子:

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

classpath:前缀*

构造基于XML的application context,路径地址可以使用classpath*: 前缀,如下:

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

classpath* 和 classpath 有什么区别呢?

classpath* 会去查找所有匹配的classpath, 而classpath 只会找到第一个匹配的资源。

FileSystemResource注意事项

未连接到FileSystemApplicationContext的FileSystemResource(即,当FileSystemApplicationContext不是实际的ResourceLoader时)会按预期处理绝对和相对路径。相对路径相对于当前工作目录,而绝对路径相对于文件系统的根目录。

但是,由于向后兼容性(历史)的原因,当FileSystemApplicationContext是ResourceLoader时,这一点会发生变化。FileSystemApplicationContext强制所有附加的FileSystemResource实例将所有位置路径视为相对路径,不管它们是否以前导斜杠开头。实际上,这意味着以下示例是等效的:

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

在实践中,如果需要真正的绝对文件系统路径,则应避免将绝对路径与FileSystemResource或FileSystemXmlApplicationContext一起使用,并通过使用file: URL 前缀强制使用UrlResource。以下示例说明了如何执行此操作:

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

本节的例子可参考resources

更多教程请参考flydean的博客

Spring5参考指南: Resources的更多相关文章

  1. Spring5参考指南:IOC容器

    文章目录 为什么使用Spring5 什么是IOC容器 配置元数据 实例化容器 XML嵌套 groovy bean定义DSL 使用容器 最近在翻译Spring Framework Documentati ...

  2. Spring5参考指南:基于注解的容器配置

    文章目录 @Required @Autowired @primary @Qualifier 泛型 @Resource @PostConstruct和@PreDestroy Spring的容器配置可以有 ...

  3. Spring5参考指南:容器扩展

    文章目录 BeanPostProcessor自定义bean BeanFactoryPostProcessor自定义配置元数据 使用FactoryBean自定义实例化逻辑 Spring提供了一系列的接口 ...

  4. Spring5参考指南:Bean的生命周期管理

    文章目录 Spring Bean 的生命周期回调 总结生命周期机制 startup和Shutdown回调 优雅的关闭Spring IoC容器 Spring Bean 的生命周期回调 Spring中的B ...

  5. Spring5参考指南:Bean作用域

    文章目录 Bean作用域简介 Singleton作用域 Prototype作用域 Singleton Beans 中依赖 Prototype-bean web 作用域 Request scope Se ...

  6. Spring5参考指南:依赖注入

    文章目录 依赖注入 依赖注入的配置详解 depends-on lazy-init 自动装载 方法注入 依赖注入 依赖注入就是在Spring创建Bean的时候,去实例化该Bean构造函数所需的参数,或者 ...

  7. Spring5参考指南:Bean的创建

    文章目录 Spring容器中的Bean Bean的命名 Bean的实例化 Spring容器中的Bean Bean在Spring中就是一个业务组件,我们通过创建各种Bean来完成最终的业务逻辑功能. 在 ...

  8. Spring5参考指南:AspectJ高级编程之Configurable

    文章目录 遇到的问题 @Configurable 原理 重要配置 遇到的问题 前面的文章我们讲到了在Spring中使用Aspect.但是Aspect的都是Spring管理的Bean. 现在有一个问题, ...

  9. Spring5参考指南:AOP代理

    文章目录 AOP代理 AOP Proxies原理 AOP代理 通常来说Spring AOP有两种代理方式,一种默认的JDK代理,只能代理接口,一种是CGLIB代理,可以代理具体的类对象. Spring ...

随机推荐

  1. 3.26java作业

    1.编写程序, 输入变量x的值,如果是1,输出x=1,如果是5,输出x=5,如果是 10,输出 x=10,除了以上几个值,都输出x=none.(知识点:if条件语句) package fda; imp ...

  2. 面试官:JavaScript 原始数据类型 Symbol 有什么用?

    以前提到 JavaScript 原始数据类型时,我们知道有Number,String,Null,Boolean,Undefined这几种.ES6 引入了新的基本数据类型Symbol和BigInt.今天 ...

  3. 《Java基础复习》-控制执行流程

    最近任务太多了,肝哭我了,boom 参考书目:Thinking in Java <Java基础复习>-控制执行流程 Java使用了C的所有流程控制语句 涉及关键字:if-else.whil ...

  4. Ali_Cloud++:阿里云部署 Jenkins持续集成自动化部署

    安装方式: 1.yum 源安装 rpm包 2.结合 tomcat 使用 war包 ....... 下载地址:Dowlnoad  (分:长期支持版本 (LTS)  和  每周更新版) jenkins插件 ...

  5. 《Three.js 入门指南》3.1.1 - 基本几何形状 -多面体

    3.1 基本几何形状 多面体 构造函数 正四面体(TetrahedronGeometry).正八面体(OctahedronGeometry).正二十面体(IcosahedronGeometry)的构造 ...

  6. js 数组 随机排序

    方法一: function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) } fu ...

  7. 10.1 io流--ASCII码表

    day2.8中提到 /* * +: * 做加法运算 * * 字符参与加法运算,其实是拿字符在计算机中存储的数据值来参与运算的 * 'A' 65(B 66...) * 'a' 97(b 98...) * ...

  8. String 对象-->判断是否相等

    1.定义和用法 == 值相等 === 绝对相等(值和类型都相等) 举例: var str = '8' var str1 = 8 console.log(str == str1) console.log ...

  9. Git应用详解第六讲:Git协作与Git pull常见问题

    前言 前情提要:Git应用详解第五讲:远程仓库Github与Git图形化界面 git除了可以很好地管理个人项目外,最大的一个用处就是实现团队协作开发.况且,linus大神开发git的初衷就是为了维护L ...

  10. Nginx如何来配置隐藏入口文件index.php(代码)

    Nginx配置文件里放入这段代码 server { location / { index index.php index.html index.htm l.php; autoindex on; if ...