Spring 使用介绍(三)—— 资源
一、Resource接口
Spring提供Resource接口,代表底层外部资源,提供对底层外部资源的一致性访问接口
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
boolean isOpen();
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
二、内置Resource实现
1、ByteArrayResource byte[]数组资源
2、FileSystemResource 文件系统资源
3、ClassPathResource classpath路径资源
4、UrlResource URL资源
- http: new UrlResource(“http://地址”)
- ftp: new UrlResource(“ftp://地址”)
- file: new UrlResource(“file:d:/test.txt”)
5、ServletContextResource 代表web应用资源,简化servlet容器的ServletContext接口的getResource操作和getResourceAsStream操作
public class ResourceTest {
private static void dumpStream(Resource resource) throws Exception {
if (resource.exists()) {
InputStream is = resource.getInputStream();
byte[] bytes = new byte[is.available()];
is.read(bytes);
System.out.println(new String(bytes));
}
}
public static void main(String[] args) throws Exception {
// byte[]数组资源
Resource resource = new ByteArrayResource("hello world".getBytes());
// 文件系统资源
//Resource resource = new FileSystemResource("D:\\hello.txt");
// classpath路径资源
//Resource resource = new ClassPathResource("durid.properties");
// URL资源
//Resource resource = new ClassPathResource("file:D:\\hello.txt");
dumpStream(resource);
System.out.println(resource.getURL());
}
}
三、ResourceLoader接口
ResourceLoader接口返回Resource,可作为生产Resource的工厂类
public interface ResourceLoader {
Resource getResource(String location);
ClassLoader getClassLoader();
}
1、ResourceLoader接口实现类:DefaultResourceLoader 通过前缀指定要加载的资源,不指定默认加载classpath资源
- classpath:path 表示返回ClasspathResource
- http://path 或 file:path 表示返回UrlResource资源
public static void main(String[] args) throws Exception {
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("file:D:\\hello.txt");
dumpStream(resource);
System.out.println(resource.getURL());
}
2、ResourceLoader注入
Spring提供ResourceLoaderAware接口,用于通过ApplicationContext上下文注入ResourceLoader,ResourceLoaderAware是一个标记接口
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}
定义实现类,并实例化为bean
public class ResourceBean implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public ResourceLoader getResourceLoader() {
return this.resourceLoader;
}
}
<bean class="cn.matt.resource.ResourceBean"></bean>
Spring检测到该接口,会将ApplicationContext注入进去
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
ResourceBean resourceBean = context.getBean(ResourceBean.class);
System.out.println(resourceBean.getResourceLoader().getClass().getName() );
}
该方式属侵入性,推荐使用自动注入方式(ApplicationContext已实现ResourceLoader ,可根据类型自动注入)
四、ResourcePatternResolver接口
1、Ant路径通配符
Ant路径通配符支持?、*、**:
?:匹配一个字符,如“config?.xml”将匹配“config1.xml”;
*:匹配零个或多个字符串,如“cn/*/config.xml”将匹配“cn/javass/config.xml”,但不匹配匹配“cn/config.xml”;而“cn/config-*.xml”将匹配“cn/config-dao.xml”;
**:匹配路径中的零个或多个目录,如“cn/**/config.xml”将匹配“cn /config.xml”,也匹配“cn/javass/spring/config.xml”;
而“cn/javass/config-**.xml”将匹配“cn/javass/config-dao.xml”,即把“**”当做两个“*”处理。
Spring提供AntPathMatcher来进行Ant风格的路径匹配
public class AntPathMatcherTest {
private PathMatcher pathMatcher = new AntPathMatcher();
@Test
public void testQuestionMark() {
Assert.assertTrue(pathMatcher.match("config?.xml", "config1.xml"));
Assert.assertFalse(pathMatcher.match("config?.xml", "config.xml"));
}
@Test
public void testOneAsterisk() {
Assert.assertTrue(pathMatcher.match("config-*.xml", "config-dao.xml"));
Assert.assertTrue(pathMatcher.match("config-*.xml", "config-.xml"));
Assert.assertTrue(pathMatcher.match("config-**.xml", "config-dao.xml"));
Assert.assertTrue(pathMatcher.match("/cn/*/config.xml", "/cn/javass/config.xml"));
Assert.assertFalse(pathMatcher.match("/cn/*/config.xml", "/cn/config.xml"));
}
@Test
public void testTwoAsterisk() {
Assert.assertTrue(pathMatcher.match("/cn/**/config-*.xml", "/cn/javass/config-dao.xml"));
Assert.assertTrue(pathMatcher.match("/cn/**/config-*.xml", "/cn/javass/spring/config-dao.xml"));
Assert.assertTrue(pathMatcher.match("/cn/**/config-*.xml", "/cn/config-dao.xml"));
}
}
2、ResourcePatternResolver接口定义
public interface ResourcePatternResolver extends ResourceLoader {
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
Resource[] getResources(String locationPattern) throws IOException;
}
ResourcePatternResolver接口继承自ResourceLoader
PathMatchingResourcePatternResolver为其实现类,默认通过AntPathMatcher进行路径匹配,除支持‘classpath’外,还支持‘classpath*’
1)classpath
a、包含通配符时,可匹配当前项目的多个资源,但无法匹配依赖包中的资源
b、无通配符时,可匹配依赖包中的资源,且仅能匹配一个资源
@Test
public void testResourcePatternResolver() throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 路径包含通配符时,只能匹配当前项目中的资源,但无法匹配依赖包中的资源
Resource[] resources = resolver.getResources("classpath:META-INF/*.txt");
Assert.assertTrue(resources.length == 2);
Resource[] resources2 = resolver.getResources("classpath:META-INF/*.schemas");
Assert.assertTrue(resources2.length == 0); // 路径无通配符时,可匹配依赖包中的资源
Resource[] resources3 = resolver.getResources("classpath:META-INF/spring.schemas");
Assert.assertTrue(resources3.length == 1); // 路径无通配符时,仅能匹配一个资源
Resource[] resources4 = resolver.getResources("classpath:META-INF/license.txt");
Assert.assertTrue(resources4.length == 1); // 路径包含通配符时,通配符前必须指定搜索目录,才能匹配到资源
Resource[] resources5 = resolver.getResources("classpath:*.xml");
Assert.assertTrue(resources5.length == 0);
}
以上示例程序运行的资源目录结构如下:
resource(当前项目)
|---- spring-context.xml
|---- META-INF
|---- license.txt
|---- license2.txt
spring-beans-4.2.5.RELEASE.jar(依赖包)
|---- META-INF
|---- spring.schemas
|---- license.txt
注意:ResourceLoader.getResource()接口不支持通配符(无论DefaultResourceLoader、PathMatchingResourcePatternResolver)
@Test
public void testResourceLoader() throws IOException {
ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); // 存在
Resource resource = resourceLoader.getResource("classpath:META-INF/license.txt");
Assert.assertTrue(resource.exists()); // 不存在
Resource resource2 = resourceLoader.getResource("classpath:META-INF/*.txt");
Assert.assertFalse(resource2.exists());
}
2)classpath*
'classpath*'可加载当前项目及依赖包下的所有匹配的资源
@Test
public void testResourcePatternResolver2() throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:**/*.xml");
Assert.assertTrue(resources.length > 1);
}
3)file:加载一个或多个文件系统中的Resource,如“file:D:/*.txt”
4)AppliacationContext继承自ResourcePatternResolver,其实现类的构造方法内部使用PathMatchingResourcePatternResolver,因而支持通配符
ApplicationContext context = new ClassPathXmlApplicationContext("spring-*.xml");
AppliacationContext的实现类:
ClassPathXmlApplicationContext 不指定前缀将返回默认的ClassPathResource资源,否则将根据前缀来加载资源
FileSystemXmlApplicationContext 不指定前缀将返回FileSystemResource,否则将根据前缀来加载资源
WebApplicationContext:不指定前缀将返回ServletContextResource,否则将根据前缀来加载资源
五、注入Resource
1、单个资源
Spring提供了ResourceEditor(继承自PropertyEditor ),用于在注入的字符串和Resource之间进行转换
2、多个资源
Spring提供了ResourceArrayPropertyEditor(继承自PropertyEditor ),用于在注入的字符串和Resource[]之间进行转换
public class Hello {
// 单个资源
private Resource resource;
// 多个资源
private Resource[] resources;
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public Resource[] getResources() {
return resources;
}
public void setResources(Resource[] resources) {
this.resources = resources;
}
}
<bean class="cn.matt.resource.Hello">
<property name="resource" value="classpath:test.xml" />
<property name="resources" value="classpath*:**/*.xml" />
</bean>
@Test
public void testResourceInjection() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Hello hello = context.getBean(Hello.class); // 单个资源
Resource resource = hello.getResource();
Assert.assertTrue(resource.exists()); // 多个资源
Resource[] resources = hello.getResources();
Assert.assertTrue(resources.length > 1);
}
参考:
第四章 资源 之 4.1 基础知识 ——跟我学spring3
第四章 资源 之 4.2 内置Resource实现 ——跟我学spring3
第四章 资源 之 4.3 访问Resource ——跟我学spring3
第四章 资源 之 4.4 Resource通配符路径 ——跟我学spring3
Spring 使用介绍(三)—— 资源的更多相关文章
- Spring DevTools 介绍
Spring DevTools 介绍 Spring Boot包括一组额外的工具,可以使应用程序开发体验更加愉快. spring-boot-devtools模块可以包含在任何项目中,它可以节省大量的时间 ...
- 深入浅出spring IOC中三种依赖注入方式
深入浅出spring IOC中三种依赖注入方式 spring的核心思想是IOC和AOP,IOC-控制反转,是一个重要的面向对象编程的法则来消减计算机程序的耦合问题,控制反转一般分为两种类型,依赖注入和 ...
- 黑马_13 Spring Boot:01.spring boot 介绍&&02.spring boot 入门
13 Spring Boot: 01.spring boot 介绍&&02.spring boot 入门 04.spring boot 配置文件 SpringBoot基础 1.1 原有 ...
- Spring Boot学习(一)——Spring Boot介绍
Spring Boot介绍 Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式 ...
- 【初探Spring】------Spring IOC(三):初始化过程---Resource定位
我们知道Spring的IoC起到了一个容器的作用,其中装得都是各种各样的Bean.同时在我们刚刚开始学习Spring的时候都是通过xml文件来定义Bean,Spring会某种方式加载这些xml文件,然 ...
- Spring MVC 处理静态资源文件
摘要: 三个方案: 1.方案一:激活Tomcat的defaultServlet来处理静态文件 2.方案二: 在spring3.0.4以后版本提供了mvc:resources (需要配置annotati ...
- Spring源码分析——资源访问利器Resource之实现类分析
今天来分析Spring的资源接口Resource的各个实现类.关于它的接口和抽象类,参见上一篇博文——Spring源码分析——资源访问利器Resource之接口和抽象类分析 一.文件系统资源 File ...
- spring与mybatis三种整合方法
spring与mybatis三种整合方法 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接 http://code.googl ...
- Spring Batch 中文参考文档 V3.0.6 - 1 Spring Batch介绍
1 Spring Batch介绍 企业领域中许多应用系统需要采用批处理的方式在特定环境中运行业务操作任务.这种业务作业包括自动化,大量信息的复杂操作,他们不需要人工干预,并能高效运行.这些典型作业包括 ...
- [翻译]Spring框架参考文档(V4.3.3)-第二章Spring框架介绍 2.1 2.2 翻译--2.3待继续
英文链接:http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/overview.ht ...
随机推荐
- 如何添加一种新Case协议
这里以添加基础http为例 首先要在脚本文件(XML文件)中定义好这种协议的基本信息 您必须在这里设计好您协议预先需要的数据(比如串口协议,那波特率,串口号等可能是不会经常改变的就可以在这里先 ...
- Netty入门(一)之webSocket聊天室
一:简介 Netty 是一个提供 asynchronous event-driven (异步事件驱动)的网络应用框架,是一个用以快速开发高性能.高可靠性协议的服务器和客户端. 换句话说,Netty 是 ...
- 持续集成之单元测试篇——WWH(讲讲我们做单元测试的故事)
持续集成之单元测试篇--WWH(讲讲我们做单元测试的故事) 前言 临近上线的几天内非重大bug不敢进行发版修复,担心引起其它问题(摁下葫芦浮起瓢) 尽管我们如此小心,仍不能避免修改一些bug而引起更多 ...
- ASP.NET Core 和 ASP.NET Framework 共享 Identity 身份验证
.NET Core 已经热了好一阵子,1.1版本发布后其可用性也越来越高,开源.组件化.跨平台.性能优秀.社区活跃等等标签再加上"微软爸爸"主推和大力支持,尽管现阶段对比.net ...
- 《React Native 精解与实战》书籍连载「React Native 中的生命周期」
此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...
- OSGI嵌入tomcat应用服务器(gem-web)——资源下载
Gem-Web官网介绍: 官网地址:https://www.eclipse.org/gemini/web/download/milestones.php 1.1. 官方正式发布版 https://ww ...
- Makefile有三个非常有用的变量。分别是$@,$^,$
原文地址:https://blog.csdn.net/u013774102/article/details/79043559 假设我们有下面这样的一个程序,源代码如下: /* main.c */ #i ...
- python线程中的全局变量与局部变量
在python多线程开发中,全局变量是多个线程共享的数据,局部变量是各自线程的,非共享的. 如下几种写法都是可以的: 第一种:将列表当成参数传递给线程 from threading import Th ...
- R语言
什么是R语言编程? R语言是一种用于统计分析和为此目的创建图形的编程语言.不是数据类型,它具有用于计算的数据对象.它用于数据挖掘,回归分析,概率估计等领域,使用其中可用的许多软件包. R语言中的不同数 ...
- 【学习总结】Git学习-参考廖雪峰老师教程四-时光机穿梭
学习总结之Git学习-总 目录: 一.Git简介 二.安装Git 三.创建版本库 四.时光机穿梭 五.远程仓库 六.分支管理 七.标签管理 八.使用GitHub 九.使用码云 十.自定义Git 期末总 ...