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. Spark菜鸟记录

    1.RDD[(k,v)] join()优化,join之前会对两个RDD的key做hash,通过网络把相同hash值的数据传到同一个节点,因此对多次join的RDD 做预分区与持久化可提高效率. map ...

  2. 引擎设计跟踪(九.14.3.1) deferred shading: Depthstencil as GBuffer depth

    问题汇总 1.Light support for Editor编辑器加入了灯光工具, 可以添加和修改灯光. 问题1. light object的用户互交.point light可以把对应的volume ...

  3. vim 常用 NERDTree 快捷键

    ctrl + w + h 光标 focus 左侧树形目录 ctrl + w + l 光标 focus 右侧文件显示窗口 ctrl + w + w 光标自动在左右侧窗口切换 ctrl + w + r 移 ...

  4. ios-时间换算

    经常会遇到时间转换的,在此收藏一个时间换算的方法〜 #pragma mark 时间换算 + (NSString *)setcreateTime:(NSString *)str { //yyyy-MM- ...

  5. python 解析命令行

    python中的命令行解析最简单最原始的方法是使用sys.argv来实现,更高级的可以使用argparse这个模块.argparse从python 2.7开始被加入到标准库中,所以如果你的python ...

  6. 迭代器使用【阿里JAVA开发手册】

    调用迭代器的remove的方法(它的方法实现是:调用ArrayList的remove(index)方法 ) 然后游标cursor相应的进行减1操作

  7. Iterator迭代器UML类图

    ArrayList类中,实现了List接口的方法 List接口的方法 迭代器接口 ArrayList的内部类实现了这个[迭代器]接口

  8. delphi 调用QQ邮箱发送邮件

    procedure TForm1.FormCreate(Sender: TObject); begin try IdSMTP1.AuthenticationType := atLogin; IdSMT ...

  9. python爬虫---selenium库的用法

    python爬虫---selenium库的用法 selenium是一个自动化测试工具,支持Firefox,Chrome等众多浏览器 在爬虫中的应用主要是用来解决JS渲染的问题. 1.使用前需要安装这个 ...

  10. [ZZ] 用matlab绘制箭头

    用matlab绘制箭头 http://npfeng900.blog.163.com/blog/static/14456108201221922944998/ 用matlab绘制箭头1 用matlab绘 ...