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两个注解进行展开,相信大家对这两个 ...
随机推荐
- 学习笔记CB003:分块、标记、关系抽取、文法特征结构
分块,根据句子的词和词性,按照规则组织合分块,分块代表实体.常见实体,组织.人员.地点.日期.时间.名词短语分块(NP-chunking),通过词性标记.规则识别,通过机器学习方法识别.介词短语(PP ...
- 转载:sql练习(针对Mysql)
感谢 https://www.cnblogs.com/DreamDrive/p/6193530.html 创建表: DROP TABLE DEPT; --部门表 CREATE TABLE DE ...
- jQuery案例2
$(this).index用来获取取到的所有元素的序号 省市联动 <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xh ...
- java基础(三):反射、反序列化破解单列模式和解决方式
单例模式指的是一个类只有一个对象,通过一些措施达到达到这个目的.但是反射和反序列化可以获得多个不同的对象. 先简单的认识一下单例模式 一:单例模式 通过私有构造器,声明一个该类的静态对象成员,提供一个 ...
- gunicorn启动flask项目的坑
问题描述:项目用的是flask框架,在项目上线的时候,服务器上是使用gunicorn来启动项目的.但是上线之后,发现服务成功启动了,也有正确的返回值,但是没有生成日志,而用python来启动服务的时候 ...
- MySQL Transaction--查看未提交事务执行的SQL
未提交事务 长期未提交事务,指开启事务后,长时间未向MySQL发出SQL执行请求或事务处理(COMMIT/ROLLBACK)请求,在系统表`information_schema`.`INNODB_TR ...
- Wavelet Ridgelet Curvelet Contourlet Ripplet
Ripplet: A New Transform for Image Processing Jun Xu, Lei Yang and Dapeng Wu Ripplet: A New Transfor ...
- 在图像中随机更改像素值程序——matlab
I=imread('C:\Users\wangd\Desktop\result3.png'); % m = rgb2gray(I); % r = unidrnd(,,); %产生一个1*100的数组, ...
- SpringMVC Mybatis Spring
Spring MVC Mybatis整合过程中 Mapper.java 不需要使用 @componenet, Service 等spring注解 但是在service 中创建mapper对象的时候是需 ...
- Android memory dump
1.读取指定pid和内存地址的字符: #include <stdlib.h> #include <stdio.h> #include <string.h> #inc ...