Spring-内置Resouce
Spring 内置Resouce
Resource: org.springframework.core.io.Resource;
内置方法
public interface Resource extends InputStreamSource {
boolean exists(); // 返回当前Resource代表的底层资源是否存在,true表示存在。
boolean isReadable();//返回当前Resource代表的底层资源是否可读,true表示可读。
boolean isOpen(); // 返回当前Resource代表的底层资源是否已经打开,如果返回true,则只能被读取一次然后关闭以避免资源泄露;常见的Resource实现一般返回false。
URL getURL() throws IOException; //如果当前Resource代表的底层资源能由java.util.URL代表,则返回该URL,否则抛出IOException。
URI getURI() throws IOException; //如果当前Resource代表的底层资源能由java.util.URI代表,则返回该URI,否则抛出IOException。
File getFile() throws IOException; //如果当前Resource代表的底层资源能由java.io.File代表,则返回该File,否则抛出IOException。
long contentLength() throws IOException;//返回当前Resource代表的底层文件资源的长度,一般是值代表的文件资源的长度。
long lastModified() throws IOException;//返回当前Resource代表的底层资源的最后修改时间。
Resource createRelative(String var1) throws IOException; //用于创建相对于当前Resource代表的底层资源的资源,比如当前Resource代表文件资源“d:/test/”则createRelative(“test.txt”)将返回表文件资源“d:/test/test.txt”Resource资源。
String getFilename(); //返回当前Resource代表的底层文件资源的文件路径,比如File资源“file://d:/test.txt”将返回“d:/test.txt”,而URL资源http://www.javass.cn将返回“”,因为只返回文件路径。
String getDescription(); //返回当前Resource代表的底层资源的描述符,通常就是资源的全路径(实际文件名或实际URL地址)。
}
ByteArrayResource:
数组资源,对于getInputStream 返回ByteArrayResource
code:
public class ResourceTest {
public static void main (String[] args){
Resource resource = new ByteArrayResource("hello".getBytes());
if(resource.exists()){
dumpStream(resource);
}
}
public static void dumpStream(Resource resource){
InputStream in = null;
try {
//获取
in = resource.getInputStream();
byte[] bytes = new byte[in.available()];
//读取
in.read(bytes);
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
//关闭
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
对于资源读取步骤,获取支援--》读取资源--》关闭资源
ByteArrayResource 是可以读取多次的,也就是isOpen 永远返回false
InputStreamResource :
代表InputStream 字节流,getInputStream直接返回字节流,这个资源只可读一次,isOpen 永远返回true;
public class ResourceTest {
public static void main (String[] args){
// Resource resource = new ByteArrayResource("hello".getBytes());
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("hello".getBytes());
Resource resource = new InputStreamResource(byteArrayInputStream);
if(resource.exists()){
dumpStream(resource);
}
System.out.print(resource.isOpen());
}
public static void dumpStream(Resource resource){
InputStream in = null;
try {
in = resource.getInputStream();
byte[] bytes = new byte[in.available()];
in.read(bytes);
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileSystemResource :
表示文件字节流 getInputStream 返回底层字节流。可以读取多次,isOpen 返回false
public class ResourceTest {
public static void main (String[] args){
//FileStreamResourceTest
File file = new File("/Users/yangqi/Desktop/test");
Resource resource = new FileSystemResource(file);
if(resource.exists()){
dumpStream(resource);
}
System.out.print(resource.isOpen());
}
public static void dumpStream(Resource resource){
InputStream in = null;
try {
in = resource.getInputStream();
byte[] bytes = new byte[in.available()];
in.read(bytes);
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ClassPathResource:
路径资源管理
ClassPathResource加载资源替代了Class类和ClassLoader类的“getResource(String name)”和“getResourceAsStream(String name)”两个加载类路径资源方法,提供一致的访问方式。
ClassPathResource提供了三个构造器:
public ClassPathResource(String path):使用默认的ClassLoader加载“path”类路径资源;
public ClassPathResource(String path, ClassLoader classLoader):使用指定的ClassLoader加载“path”类路径资源;
比如当前类路径是 “cn.javass.spring.chapter4.ResourceTest”,而需要加载的资源路径是“cn/javass/spring /chapter4/test1.properties”,则将加载的资源在“cn/javass/spring/chapter4 /test1.properties”,即加载在相同路径下;
public ClassPathResource(String path, Class<?> clazz):使用指定的类加载“path”类路径资源,将加载相对于当前类的路径的资源;
比如当前类路径是 “cn.javass.spring.chapter4.ResourceTest”,而需要加载的资源路径是“cn/javass/spring /chapter4/test1.properties”,则将加载的资源在“cn/javass/spring/chapter4/cn/javass /spring/chapter4/test1.properties” ;
而如果需要 加载的资源路径为“test1.properties”,将加载的资源为“cn/javass/spring/chapter4/test1.properties” 即路径累加下,如字符串append到新的里面累加成新的路径。
UrlResource:
UrlResource代表URL资源,用于简化URL资源访问。“isOpen”永远返回false,表示可多次读取资源。
UrlResource一般支持如下资源访问:
http:通过标准的http协议访问web资源,如new UrlResource(“http://地址”);
ftp:通过ftp协议访问资源,如new UrlResource(“ftp://地址”);
file:通过file协议访问本地文件系统资源,如new UrlResource(“file:d:/test.txt”);
ServletContextResource
ServletContextResource代表web应用资源,用于简化servlet容器的ServletContext接口的getResource操作和getResourceAsStream操作;在此就不具体演示了。
VfsResource
VfsResource代表Jboss 虚拟文件系统资源。
Jboss VFS(Virtual File System)框架是一个文件系统资源访问的抽象层,它能一致的访问物理文件系统、jar资源、zip资源、war资源等,VFS能把这些资源一致的映射 到一个目录上,访问它们就像访问物理文件资源一样,而其实这些资源不存在于物理文件系统。
ResourceLoader接口
public interface ResourceLoader {
Resource getResource(String location); //用于根据提供的location参数返回相应的Resource对象
ClassLoader getClassLoader(); //返回加载这些Resource的ClassLoader
}
这可以看做是一个返回resource的工厂类 Spring提供了一个适用于所有环境的DefaultResourceLoader实现,可以返回ClassPathResource、 UrlResource;还提供一个用于web环境的ServletContextResourceLoader,
它继承了 DefaultResourceLoader的所有功能,又额外提供了获取ServletContextResource的支持。 Spring提供了一个适用于所有环境的DefaultResourceLoader实现,可以返回ClassPathResource、 UrlResource;还提供一个用于web环境的ServletContextResourceLoader,
它继承了 DefaultResourceLoader的所有功能,又额外提供了获取ServletContextResource的支持。
ResourceLoader 在加载的时候需要指定需要加载的资源
1 如果前缀是calsspath:path 则返回ClassPathResouce
2 如果前缀是http:// 或者是 file:// 则返UrlResource
3 如果什么都不加,会根据上下文决定,DefaultResourceLoader可以默认实现加载classpath
测试代码如下:
@Test
public void testResourceLoad1() {
ResourceLoader loader = new DefaultResourceLoader(); Resource resource = loader.getResource("classpath:lqy/springh4_3/test1.txt");
//验证返回的是ClassPathResource
Assert.assertEquals(ClassPathResource.class, resource.getClass());
}
@Test
public void testResourceLoad2() {
ResourceLoader loader = new DefaultResourceLoader(); Resource resource2 = loader.getResource("file:lqy/springh4_3/test1.txt");
//验证返回的是ClassPathResource
Assert.assertEquals(UrlResource.class, resource2.getClass()); }
@Test
public void testResourceLoad3() {
ResourceLoader loader = new DefaultResourceLoader(); Resource resource3 = loader.getResource("lqy/springh4_3/test1.txt");
//验证返默认可以加载ClasspathResource
Assert.assertTrue(resource3 instanceof ClassPathResource);
} }
注:
对于目前所有ApplicationContext都实现了ResourceLoader,因此可以使用其来加载资源。
ClassPathXmlApplicationContext:不指定前缀将返回默认的ClassPathResource资源,否则将根据前缀来加载资源;
FileSystemXmlApplicationContext:不指定前缀将返回FileSystemResource,否则将根据前缀来加载资源;
WebApplicationContext:不指定前缀将返回ServletContextResource,否则将根据前缀来加载资源;
其他:不指定前缀根据当前上下文返回Resource实现,否则将根据前缀来加载资源。
ResourceLoaderAware
ResourceLoaderAware是一个标记接口,用于通过ApplicationContext上下文注入ResourceLoader。
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}
测试方法:
public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("classpath:com/info/ResourceLoaderAware/awareTest.xml");
ResourceBean bean = context.getBean(ResourceBean.class);
ResourceLoader resourceLoader = bean.getResourceLoader();
System.out.print(resourceLoader instanceof ApplicationContext); }
Spring通过ResourceArrayPropertyEditor来进行类型转换的,而它又默认使用 “PathMatchingResourcePatternResolver”来进行把路径解析为Resource对象。所有大家只要会使用 “PathMatchingResourcePatternResolver”,其它一些实现都是委托给它的,比如 AppliacationContext的“getResources”方法等。
AppliacationContext实现对各种Resource的支持
public class ClassPathXmlApplicationContext {
//1)通过ResourcePatternResolver实现根据configLocation获取资源
public ClassPathXmlApplicationContext(String configLocation);
public ClassPathXmlApplicationContext(String... configLocations);
public ClassPathXmlApplicationContext(String[] configLocations, ……);
//2)通过直接根据path直接返回ClasspathResource
public ClassPathXmlApplicationContext(String path, Class clazz);
public ClassPathXmlApplicationContext(String[] paths, Class clazz);
public ClassPathXmlApplicationContext(String[] paths, Class clazz, ……);
}
第一类构造器是根据提供的配置文件路径使用“ResourcePatternResolver ”的“getResources()”接口通过匹配获取资源;即如“classpath:config.xml”
第二类构造器则是根据提供的路径和clazz来构造ClassResource资源。即采用“public ClassPathResource(String path, Class<?> clazz)”构造器获取资源。
二、FileSystemXmlApplicationContext:将 加载相对于当前工作目录的“configLocation”位置的资源,注意在linux系统上不管“configLocation”是否带“/”,都作 为相对路径;而在window系统上如“D:/resourceInject.xml”是绝对路径。因此在除非很必要的情况下,不建议使用该 ApplicationContext。
public class FileSystemXmlApplicationContext{
public FileSystemXmlApplicationContext(String configLocation);
public FileSystemXmlApplicationContext(String... configLocations,……);
}
//linux系统,以下全是相对于当前vm路径进行加载
new FileSystemXmlApplicationContext("chapter4/config.xml");
new FileSystemXmlApplicationContext("/chapter4/confg.xml");
//windows系统,第一个将相对于当前vm路径进行加载;
//第二个则是绝对路径方式加载
new FileSystemXmlApplicationContext("chapter4/config.xml");
new FileSystemXmlApplicationContext("d:/chapter4/confg.xml");
此处还需要注意:在linux系统上,构造器使用的是相对路径,而ctx.getResource()方法如果以“/”开头则表示获取绝对路径资源,而不带前导“/”将返回相对路径资源。如下:

//linux系统,第一个将相对于当前vm路径进行加载;
ctx.getResource ("chapter4/config.xml");
ctx.getResource ("/root/confg.xml");
//windows系统,第一个将相对于当前vm路径进行加载;
//第二个则是绝对路径方式加载
ctx.getResource ("chapter4/config.xml");
ctx.getResource ("d:/chapter4/confg.xml");

因此如果需要加载绝对路径资源最好选择前缀“file”方式,将全部根据绝对路径加载。如在linux系统“ctx.getResource ("file:/root/confg.xml");”
Spring-内置Resouce的更多相关文章
- Spring —— 三种配置数据源的方式:spring内置、c3p0、dbcp
01.Spring内置数据源配置Class:DriverManagerDataSource全限定名:org.springframework.jdbc.datasource.DriverManagerD ...
- Spring中内置的一些工具类
学习Java的人,或者开发很多项目,都需要使用到Spring 这个框架,这个框架对于java程序员来说.学好spring 就不怕找不到工作.我们时常会写一些工具类,但是有些时候 我们不清楚,我们些的工 ...
- ActiveMQ第三弹:在Spring中使用内置的Message Broker
在上个例子中我们演示了如何使用Spring JMS来向ActiveMQ发送消息和接收消息.但是这个例子需要先从控制台使用ActiveMQ提供的命令行功能启动一个Message Broker,然后才能运 ...
- Spring Boot修改内置Tomcat端口号 (zhuan)
http://blog.csdn.net/argel_lj/article/details/49851625 ********************************************* ...
- Spring Security 入门(1-6-2)Spring Security - 内置的filter顺序、自定义filter、http元素和对应的filterChain
Spring Security 的底层是通过一系列的 Filter 来管理的,每个 Filter 都有其自身的功能,而且各个 Filter 在功能上还有关联关系,所以它们的顺序也是非常重要的. 1.S ...
- Spring Boot 添加jersey-mvc-freemarker依赖后内置tomcat启动不了解决方案
我在我的Spring Boot 项目的pom.xml中添加了jersey-mvc-freemarker依赖后,内置tomcat启动不了. 报错信息如下: org.springframework.con ...
- Spring boot 内置tomcat禁止不安全HTTP方法
Spring boot 内置tomcat禁止不安全HTTP方法 在tomcat的web.xml中可以配置如下内容,让tomcat禁止不安全的HTTP方法 <security-constraint ...
- Spring Boot修改内置Tomcat端口号
spring Boot 内置Tomcat默认端口号为8080,在开发多个应用调试时很不方便,本文介绍了修改 Spring Boot内置Tomcat端口号的方法. 一.EmbeddedServletCo ...
- Spring Cloud内置的Zuul过滤器详解
Spring Cloud默认为Zuul编写并启用了一些过滤器,这些过滤器有什么作用呢?我们不妨按照@EnableZuulServer.@EnableZuulProxy两个注解进行展开,相信大家对这两个 ...
随机推荐
- Linux下搭建测试环境
一. 安装虚拟机 1.选择linux 型号 3.0x 64的版本 2.磁盘分区 /目录, home目录 ,boot,var ,设置root密码 3.安装(过程略) 二. 配置虚拟机网卡 路径:cd / ...
- CF999E Reachability from the Capital来自首都的可达性
题目大意: 有n个节点m条边,边都是单向的,请你添加最少的边使得起点s到其他与其他每一个点之间都能互相到达 这题一看就是一个缩点啊 其实对于原有的m条边相连的一些点,如果之前他们已经形成了强连通分量( ...
- gdb 调试 python
gdb 版本 >7 的 对python调试有特别支持,参考: https://docs.python.org/devguide/gdb.html?highlight=gdb https://bl ...
- LeetCode - Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors. # m ...
- ARM Cortex M0 程序映像和启动流程
- 代理IP
代理IP 一.获取代理IP 二.使用代理IP 1.requests 2. selenium 2.1 selenium+chrome 2.2 selenium+Firefox 2.3 selenium+ ...
- DockerFile详解--转载
COPY 复制文件 格式: COPY ... COPY ["",... ""] 和 RUN 指令一样,也有两种格式,一种类似于命令行,一种类似于函数调用. CO ...
- siftflow-fcn32s训练及预测
一.说明 SIFT Flow 是一个标注的语义分割的数据集,有两个label,一个是语义分类(33类),另一个是场景标签(3类). Semantic and geometric segmentatio ...
- 浅谈SPI总线
SPI总线概述 SPI全称是串行外设接口(Serial Peripheral Interface),是由Motorola提出的一种全双工同步串行通信接口,通信波特率可以高达5Mbps,但具体速 ...
- 在已安装64位oracle的服务器安装32位客户端
应用场景:服务器操作系统是win2012 64位,原先安装了64位oracle12,后来系统增加导入excel的功能,网站必须启用32位兼容模式,这时候发现原有的页面打不开,提示: 试图加载格式不正确 ...