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. Johnson-Trotter(JT)算法求全排列

    Johnson-Trotter算法描述 算法 JohnsonTrotter(n) //实现用来生成排序的 Johnson-Trotter 算法 //输入:正整数n(代表序列1,2,···,n) //输 ...

  2. Java多线程工具类之循环栅栏计数器

    Java多线程下循环计数器 本文主要内容:CyclicBarrier(下文中凯哥就用cycBar来代替)定义介绍:举例说明:代码演示:从源码来看原理及总结:CyclicBarrier与CountDow ...

  3. Go语言笔记 (2) 变量命名与多重赋值

    变量命名 1.大小写 观摩以下代码: func main() { var m int = "你" var M int = "我" fmt.Println(m,M ...

  4. HSRP热备份路由协议

    HSRP热备份路由协议 案例1:HSRP配置 案例2:三层交换配置HSRP 案例3:STP的配置 案例4:三层交换配置STP 1 案例1:HSRP配置 1.1 问题 在企业网络到外部的连接方案中,要求 ...

  5. SpringCloud(三)之我学 Hystrix

    1.断路器 在消费服务的启动类,添加注解:@EnableCircuitBreaker,在消费服务的调用类上,添加注解:@HystrixCommand(fallbackMethod = "&q ...

  6. 这些基本的 HTML5 标签你不能不知道

    HTML5元素 HTML5是HTML最新的修订版本,2014年10月由万维网联盟(W3C)完成标准制定. HTML5是用来写网页的一门标记语言. 使用的时候需要在首行声明HTML,如:<!DOC ...

  7. Linux服务器架设篇,Nginx服务器的架设

    1.安装 nginx依赖包 (1)安装pcre yum install pcre-devel (2)安装openssl yum -y install openssl-devel (3)安装zlib y ...

  8. Linux 压缩备分篇(一 备份数据)

    备份文件                dump dump: -S                    仅列出待备份数据需要多少磁盘空间才能够备份完毕 -u                    将 ...

  9. Java中的垃圾回收算法详解

    一.前言   前段时间大致看了一下<深入理解Java虚拟机>这本书,对相关的基础知识有了一定的了解,准备写一写JVM的系列博客,这是第二篇.这篇博客就来谈一谈JVM中使用到的垃圾回收算法. ...

  10. 小程序wepy2 模拟vant PasswordInput, NumberKeyboard 密码输入框控件

    vant weapp小程序端控件目前是没有PasswordInput,NumberKeyboard的.实现效果: 数字键盘组件代码(keyboard.wpy): <template> &l ...