Spring中Resource(资源)的获取

Easter79
• 阅读 807

1.通过Resource接口获取资源

Resource接口的实现类有:

Spring中Resource(资源)的获取

 Resource接口继承了InputStreamSource 接口,InputStreamSource 接口中有一个方法:getInputStream(),所以汇总起来,Resource接口中共有以下方法:

Spring中Resource(资源)的获取

public class ResourceTest {

    /**使用ClassPathResource获取资源**/
    @Test
    public void TestClassPath() throws IOException{
        Resource resource = new ClassPathResource("test.txt");

        //判断文件是否存在:
        if (resource.exists()) {
            System.out.println("文件存在");
        }

        //判断资源文件是否可读
        if (resource.isReadable()) {  
            System.out.println("文件可读"); 
        }

        //判断当前Resource代表的底层资源是否已经打开
        if (resource.isOpen()) {
            System.out.println("资源文件已打开");
        }

        System.out.println(resource.getURL());//获取资源所在的URL
        System.out.println(resource.getURI());//获取资源所在的URI
        resource.getFile();//返回当前资源对应的File。
        System.out.println(resource.contentLength());//输出内容长度
        System.out.println(resource.lastModified());//返回当前Resource代表的底层资源的最后修改时间。
        resource.createRelative("MyFile");//根据资源的相对路径创建新资源。[默认不支持创建相对路径资源]
        System.out.println(resource.getFilename());//获取资源文件名
        System.out.println(resource.getDescription());


        //获取当前资源代表的输入流
        if (resource.isReadable()) {
            InputStream is = resource.getInputStream();  
            System.out.println(is);
            is.close();
        }

    }

    /**使用FileSystemResource获取资源**/
    @Test
    public void TestFileSystem() throws IOException {
        Resource resource = new FileSystemResource("D:\\test.txt");
        System.out.println(resource.getFilename());
    }

    /**使用UrlResource获取资源**/
    @Test
    public void TestUrl() throws MalformedURLException{
        Resource resource = new UrlResource("http://docs.spring.io/spring/docs/4.0.0.M1/spring-framework-reference/pdf/spring-framework-reference.pdf");
        System.out.println(resource.getFilename());
    }

    /**使用ByteArrayResource获取字节数组封装的资源**/
    @Test
    public void testByteArray() throws IOException {
        ByteArrayResource resource = new ByteArrayResource("Hello".getBytes()); 
        System.out.println(resource.getInputStream());

    }


    /**使用InputStreamResource获取输入流封装的资源。针对于输入流的Resource,其getInputStream()方法只能被调用一次。**/  
       @Test  
       public void testInputStream() throws Exception {  
          InputStream is = new FileInputStream("D\\test.txt");  
          InputStreamResource resource = new InputStreamResource(is);  
          //对于InputStreamResource而言,其getInputStream()方法只能调用一次,继续调用将抛出异常。  
          InputStream is2 = resource.getInputStream();   //返回的就是构件时的那个InputStream
          System.out.println(is2);
          is.close();
       } 
}

2.通过ResourceLoader接口获取资源

Spring框架为了更方便的获取资源,尽量弱化程序员对各个Resource接口的实现类的感知,定义了另一个ResourceLoader接口。该接口的getResource(String location)方法可以用来获取资源。它的DefaultResourceLoader实现类可以适用于所有的环境,可以返回ClassPathResource、UrlResource等。

ResourceLoader在进行加载资源时需要使用前缀来指定需要加载:“classpath:path”表示返回ClasspathResource,“http://path”和“file:path”表示返回UrlResource资源,如果不加前缀则需要根据当前上下文来决定,DefaultResourceLoader默认实现是加载classpath资源。

       @Test  
       public void testResourceLoader() { 

              ResourceLoader loader = new DefaultResourceLoader();  
              Resource resource = loader.getResource("http://www.baidu.com");  
              System.out.println(resource instanceof UrlResource); //true  
              resource = loader.getResource("classpath:test.txt");  
              System.out.println(resource instanceof ClassPathResource); //true  
              resource = loader.getResource("test.txt");  
              System.out.println(resource instanceof ClassPathResource); //true  

       } 

3.通过ApplicationContext获取资源

所有ApplicationContext实例都实现了ResourceLoader接口,因此我们在使用Spring容器时,可以不去过于计较底层Resource的实现,也不需要自己创建Resource实现类,而是直接使用applicationContext.getResource(),获取到bean容器本身的Resource,进而取到相关的资源信息。

public class MyResource implements ApplicationContextAware {
        private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void resource() throws IOException {
        Resource resource = applicationContext.getResource("file:D:\\test.txt");
        System.out.println(resource.getFilename());
        System.out.println(resource.contentLength());

    }

}

配置xml文件:

<bean id="myResource" class="com.spring.test.MyResource"></bean>

测试类:

public class App {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-resource.xml");  
        MyResource myResource = (MyResource) context.getBean("myResource");
        try {
            myResource.resource();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Stella981 Stella981
2年前
Android 虹软人脸识别SDK
准备:登录官方网站,获取SDK,进行个人验证后新建项目,获取APP\_ID,和SDK\_KEY;https://ai.arcsoft.com.cn/ucenter/resource/build/index.html/ucenter/resource/openPlatform/application(https://www.o
Wesley13 Wesley13
2年前
JavaWeb 调用接口
JavaWeb 如何调用接口CreateTime2018年4月2日19:04:29Author:Marydon1.所需jar包!(https://oscimg.oschina.net/oscnet/0f139
Stella981 Stella981
2年前
ClickHouse大数据领域企业级应用实践和探索总结
点击上方蓝色字体,选择“设为星标”回复”资源“获取更多资源!(https://oscimg.oschina.net/oscnet/bb00e5f54a164cb9827f1dbccdf87443.jpg)!(https://oscimg.oschina.net/oscnet/dc8da835ff1b4
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k