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");”

最新文章

  1. 使用 Spring 进行单元测试
  2. html中使用js实现内容过长时部分
  3. 正则表达式匹配a标签的href
  4. Mate7微信指纹支付来了 比Touch ID整合微信早一点
  5. [运维-服务器 – 1A] – nginx.conf(转)
  6. Apache+tomcat集群配置
  7. maven缺少依赖包,强制更新命令
  8. jQuery选择器之可见性过滤选择器Demo
  9. C#获取ip的示例
  10. npm install --save 与 npm install --save-dev 的区别
  11. leetcode Maximum Depth of Binary Tree python
  12. ThinkPad E530 Fedora 20 无线上网问题
  13. Java面试题 BAT 大公司面试题整理总结!
  14. .NetCore实践爬虫系统(一)解析网页内容
  15. JMeter学习-041-响应数据中文乱码解决方法
  16. Shell脚本学习-数组
  17. JavaScript开发区块链只需200行代码
  18. PyTorch 常用方法总结1:生成随机数Tensor的方法汇总(标准分布、正态分布……)
  19. Git-git rebase详解
  20. Codeforces Round #375 (Div. 2) E. One-Way Reform 欧拉路径

热门文章

  1. 2_PY基本数据类型
  2. 《Self-Attention Generative Adversarial Networks》里的注意力计算
  3. java-同一用户顶替操作(session过期或无效)
  4. 视频外同步信号研究---fvh
  5. 【SQL实践】其他常用SQL汇总
  6. 【CentOS】设置定时执行任务
  7. 使用R的注意事项
  8. 使用命令行执行jmeter的方法
  9. Linux 学习目录
  10. CentOS7.5 GlusterFS 分布式文件系统集群环境搭建