Spring资源抽象Resource

本文详细介绍了Spring框架中的Resource接口及其多种实现类,包括ClassPathResource、FileSystemResource、UrlResource等,展示了如何通过这些类加载不同类型的资源,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

Spring对各种底层资源,比如文件系统中的一个文件,classpath上的一个文件,或者一个网络URL,统一抽象为接口Resource来表示 。

org.springframework.core.io // 接口Resource所在包

因为每个底层文件都可以以一个只读InputStream的方式打开,所以Resource接口继承自接口InputStreamSourceInputStreamSource接口中定义了方法getInputStream()用于返回打开该资源所对应的输入流。

实现类

Spring针对不同的底层资源类型提供了相应的实现。如下表所示 :

实现类介绍
ClassPathResourceJava类路径上的一个资源文件,
比如一个class文件,xml/properties配置文件,亦或一个图片文件等等
FileSystemResource操作系统文件系统中的一个资源文件
一个xml/properties配置文件,一个图片,一个pdf,一个jar包等等
UrlResource将一个网络URL地址封装成一个资源文件
一个静态图片,html,js,css,或者能动态生成json/xml
ByteArrayResource将一个字节数组封装成一个Resource
ServletContextResource获取ServletContext环境下的资源文件,在web应用程序的根目录下解释相对路径
InputStreamResource将一个输入流封装成一个资源,因为用于描述一个已经打开的资源,所以isOpen()总是返回true
VfsResource针对JBoss VFS 的资源

Resource及其实现

使用实例

package test.resources;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.core.io.*;

import java.io.FileInputStream;
import java.io.InputStream;

@Slf4j
public class SpringResourceDemo {
    /**
     * 描述一个Resource实例
     *
     * @param resource
     * @throws Exception
     */
    void describe(Resource resource) throws Exception {
        log.info("====================================");
        log.info("toString : {}", resource.toString());
        log.info("contentLength : {}", resource.contentLength());
        log.info("exists : {}", resource.exists());
        log.info("getDescription : {}", resource.getDescription());
        log.info("isReadable : {}", resource.isReadable());
        log.info("isOpen : {}", resource.isOpen());
        log.info("getFilename : {}", resource.getFilename());
        log.info("isFile : {}", resource.isFile());
        if (resource.isFile()) {
            // getFile()仅针对文件类型Resource有效,可以是文件系统文件或者classpath上的文件
            log.info("getFile : {}", resource.getFile());
        }

        if (!((resource instanceof ByteArrayResource) || (resource instanceof InputStreamResource))) {
            // 以下三个属性针对 ByteArrayResource/InputStreamResource 类型资源无效,调用的话会抛出异常
            log.info("lastModified : {}", resource.lastModified());
            log.info("getURI : {}", resource.getURI());
            log.info("getURL : {}", resource.getURL());
        }
    }

    @Test
    public void test() throws Exception {
        {
            Resource resource = new ClassPathResource("test/resources/SpringResourceDemo.class");
            describe(resource);
        }

        {// test.txt 是当前磁盘卷根目录下一个存在的文件,内容是:Test Spring Resource
            Resource resource = new FileSystemResource("/test.txt");
            describe(resource);
        }

        {//
            Resource resource = new UrlResource("https://docs.spring.io");
            describe(resource);
        }

        {//
            Resource resource = new ByteArrayResource("Hello".getBytes());
            describe(resource);
        }


        {// test.txt 是当前磁盘卷根目录下一个存在的文件,内容是:Test Spring Resource
            InputStream is = new FileInputStream("/test.txt");
            Resource resource = new InputStreamResource(is);
            describe(resource);
        }
    }
}

上面的测试代码执行输出如下:

====================================
toString : class path resource [test/resources/SpringResourceDemo.class]
contentLength : 2838
exists : true
getDescription : class path resource [test/resources/SpringResourceDemo.class]
isReadable : true
isOpen : false
getFilename : SpringResourceDemo.class
isFile : true
getFile : D:\springboot-tut-zero\target\test-classes\test\resources\SpringResourceDemo.class
lastModified : 1542634668385
getURI : file:/D:/springboot-tut-zero/target/test-classes/test/resources/SpringResourceDemo.class
getURL : file:/D:/springboot-tut-zero/target/test-classes/test/resources/SpringResourceDemo.class
====================================
toString : file [D:\test.txt]
contentLength : 20
exists : true
getDescription : file [D:\test.txt]
isReadable : true
isOpen : false
getFilename : test.txt
isFile : true
getFile : \test.txt
lastModified : 1542633020067
getURI : file:/D:/test.txt
getURL : file:/D:/test.txt
====================================
toString : URL [https://docs.spring.io]
contentLength : -1
exists : true
getDescription : URL [https://docs.spring.io]
isReadable : true
isOpen : false
getFilename : 
isFile : false
lastModified : 0
getURI : https://docs.spring.io
getURL : https://docs.spring.io
====================================
toString : Byte array resource [resource loaded from byte array]
contentLength : 5
exists : true
getDescription : Byte array resource [resource loaded from byte array]
isReadable : true
isOpen : false
getFilename : null
isFile : false
====================================
toString : InputStream resource [resource loaded through InputStream]
contentLength : 20
exists : true
getDescription : InputStream resource [resource loaded through InputStream]
isReadable : true
isOpen : true
getFilename : null
isFile : false

参考资源

Spring资源加载器抽象和缺省实现 – ResourceLoader + DefaultResourceLoader

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值