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的更多相关文章

  1. Spring —— 三种配置数据源的方式:spring内置、c3p0、dbcp

    01.Spring内置数据源配置Class:DriverManagerDataSource全限定名:org.springframework.jdbc.datasource.DriverManagerD ...

  2. Spring中内置的一些工具类

    学习Java的人,或者开发很多项目,都需要使用到Spring 这个框架,这个框架对于java程序员来说.学好spring 就不怕找不到工作.我们时常会写一些工具类,但是有些时候 我们不清楚,我们些的工 ...

  3. ActiveMQ第三弹:在Spring中使用内置的Message Broker

    在上个例子中我们演示了如何使用Spring JMS来向ActiveMQ发送消息和接收消息.但是这个例子需要先从控制台使用ActiveMQ提供的命令行功能启动一个Message Broker,然后才能运 ...

  4. Spring Boot修改内置Tomcat端口号 (zhuan)

    http://blog.csdn.net/argel_lj/article/details/49851625 ********************************************* ...

  5. Spring Security 入门(1-6-2)Spring Security - 内置的filter顺序、自定义filter、http元素和对应的filterChain

    Spring Security 的底层是通过一系列的 Filter 来管理的,每个 Filter 都有其自身的功能,而且各个 Filter 在功能上还有关联关系,所以它们的顺序也是非常重要的. 1.S ...

  6. Spring Boot 添加jersey-mvc-freemarker依赖后内置tomcat启动不了解决方案

    我在我的Spring Boot 项目的pom.xml中添加了jersey-mvc-freemarker依赖后,内置tomcat启动不了. 报错信息如下: org.springframework.con ...

  7. Spring boot 内置tomcat禁止不安全HTTP方法

    Spring boot 内置tomcat禁止不安全HTTP方法 在tomcat的web.xml中可以配置如下内容,让tomcat禁止不安全的HTTP方法 <security-constraint ...

  8. Spring Boot修改内置Tomcat端口号

    spring Boot 内置Tomcat默认端口号为8080,在开发多个应用调试时很不方便,本文介绍了修改 Spring Boot内置Tomcat端口号的方法. 一.EmbeddedServletCo ...

  9. Spring Cloud内置的Zuul过滤器详解

    Spring Cloud默认为Zuul编写并启用了一些过滤器,这些过滤器有什么作用呢?我们不妨按照@EnableZuulServer.@EnableZuulProxy两个注解进行展开,相信大家对这两个 ...

随机推荐

  1. 電腦清理緩存bat文件源碼

    @echo off echo 正在清除系統垃圾文件,請稍等 ...... del /f /s /q %systemdrive%\*.tmp del /f /s /q %systemdrive%\*._ ...

  2. 2018-2019-2 《网络对抗技术》Exp0 Kali安装 Week1 20165308 张士洋

    2018-2019-2 <网络对抗技术>Exp0 Kali安装 Week1 20165308 张士洋 1.进入官网下载Kali Linux VirtualBox版本的镜像文件. 2.解压并 ...

  3. LVS中Windows作为真实主机(RealServer)时的设置方法

    最近,公司新推了一个电商项目,IIS+ASP.而上面大大规划了要用 LVS 负载均衡集群,在这个技术陈旧的企业,LVS 项目还是去年才真正推行.由于最开始是由我测试的,所以这次的部署又落到了我头上了. ...

  4. TCP/IP 通信

    TCP/IP 通信又叫socket 通信,是基于TCP/IP协调面向连接的一个数据传输技术.是属于OSI国际标准的传输层,三次握手 提供数据,有序,安全,端到端的传输和接收.它有三个主要协议:传输控制 ...

  5. 关于UI自动化中元素定位常用方法的个人总结

    1.如果目标元素有id属性,优先使用id定位: 2.元素locator尽可能保证简洁,考虑locator中路径的变化频率,尽量减少后期更新和维护成本: 3.使用xpath时,不要一味的使用‘/’逐层进 ...

  6. Mha-Atlas-MySQL高可用

    Mha-Atlas-MySQL高可用 一.MHA简介 1.软件介绍 MHA在MySQL高可用是一个相对成熟的解决方案,是一套优秀的作为mysql高可用环境下故障切换和主从提升的高可用软件,在MySQL ...

  7. JavaScript最后的课程笔记

    一.快捷位置和尺寸 DOM已经提供给我们计算后的样式,但是还觉得不方便,所以DOM又提供给我们一些API: ele.offsetLeft ele.offsetTop ele.offsetWidth e ...

  8. 操作系统实现线程的几种模式 和 java创建线程的3个方式

    操作系统实现线程的几种模式 和 java创建线程的3个方式  这是两个概念 在操作系统中,线程可以实现在用户模式下,也可以实现在内核模式下,也可以两者结合实现. 1.实现线程的三种方式: (1)继承t ...

  9. dp练习--

    动态规划(DP)算法     动态规划是运筹学的一个分支,是求解决策过程最优化的数学方法.利用各个阶段之间的关系,逐个求解,最终求得全局最优解,需要确认原问题与子问题.动态规划状态.边界状态.边界状态 ...

  10. 码云Gitee上新建项目教程

    1.在浏览器访问,https://gitee.com/: 2.使用用户名.密码登录: 3.在左下角显示当前用户的项目,点击“+”号,创建项目: 4.填写项目的相关信息,项目名称要和本地要上传的项目名称 ...