8、资源操作 Resource

8.1、Spring Resources概述

Java的标准java.net.URL类和各种URL前缀的类无法满足所有对low-level资源的访问。

比如:没有标准化的 URL 实现访问需要从类路径相对于 ServletContext 获取的资源。并且缺少某些Spring所需要的功能,例如检测某资源是否存在等。

Spring的Resource声明了访问low-level资源的能力。

在这里插入图片描述

补充:什么是 low-level 资源?

在Spring框架中,Resource接口是一个抽象接口,用于统一访问各种低级别(low-level)的资源。低级别资源指的是那些需要通过底层I/O操作进行读取和写入的资源。具体来说,这些资源可以包括:

1. 文件系统资源

  • 本地文件:在文件系统中的文件,例如文本文件、配置文件、图像文件等。
    Resource resource = new FileSystemResource("/path/to/file.txt");
    

2. 类路径资源

  • 类路径中的资源:通常是项目中的配置文件、静态资源等,位于类路径下。
    Resource resource = new ClassPathResource("config/application.properties");
    

3. URL资源

  • 网络资源:通过URL访问的资源,可以是HTTP、HTTPS、FTP等协议。
    Resource resource = new UrlResource("http://example.com/resource.txt");
    

4. 内嵌资源

  • 内嵌在JAR包或WAR包中的资源:通过类路径访问的资源,常用于读取内部配置文件或嵌入式资源。
    Resource resource = new ClassPathResource("META-INF/spring.factories");
    

5. InputStream资源

  • 输入流资源:从输入流中读取的资源,通常用于处理非文件系统的流数据。
    InputStream inputStream = new ByteArrayInputStream("sample data".getBytes());
    Resource resource = new InputStreamResource(inputStream);
    

6. ServletContext资源

  • Web应用程序上下文中的资源:在Web应用的Servlet上下文中访问资源。
    Resource resource = new ServletContextResource(servletContext, "/WEB-INF/config.xml");
    

示例代码

下面是一些示例代码,展示了如何使用Spring的Resource接口访问不同类型的资源:

import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.InputStreamResource;

import java.io.IOException;
import java.io.InputStream;

public class ResourceExample {

    public static void main(String[] args) throws IOException {
        // 1. 访问文件系统中的资源
        Resource fileSystemResource = new FileSystemResource("/path/to/file.txt");
        printResourceContent(fileSystemResource);

        // 2. 访问类路径中的资源
        Resource classPathResource = new ClassPathResource("config/application.properties");
        printResourceContent(classPathResource);

        // 3. 访问URL中的资源
        Resource urlResource = new UrlResource("http://example.com/resource.txt");
        printResourceContent(urlResource);

        // 4. 访问输入流资源
        InputStream inputStream = new ByteArrayInputStream("sample data".getBytes());
        Resource inputStreamResource = new InputStreamResource(inputStream);
        printResourceContent(inputStreamResource);
    }

    private static void printResourceContent(Resource resource) throws IOException {
        try (InputStream is = resource.getInputStream()) {
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String content = new String(buffer);
            System.out.println("Resource content: " + content);
        }
    }
}

结论

Spring的Resource接口提供了一种统一的方式来访问各种低级别的资源,无论这些资源是本地文件、类路径资源、URL资源还是输入流资源。通过使用Resource接口,开发人员可以轻松地读取和管理不同类型的资源,提升了代码的可维护性和灵活性。


8.2、Resource接口

Spring 的 Resource 接口位于 org.springframework.core.io 中。 旨在成为一个更强大的接口,用于抽象对低级资源的访问。以下显示了Resource接口定义的方法

public interface Resource extends InputStreamSource {
    boolean exists();

    default boolean isReadable() {
        return this.exists();
    }

    default boolean isOpen() {
        return false;
    }

    default boolean isFile() {
        return false;
    }

    URL getURL() throws IOException;

    URI getURI() throws IOException;

    File getFile() throws IOException;

    default ReadableByteChannel readableChannel() throws IOException {
        return Channels.newChannel(this.getInputStream());
    }

    long contentLength() throws IOException;

    long lastModified() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    @Nullable
    String getFilename();

    String getDescription();
}

Resource接口继承了InputStreamSource接口,提供了很多InputStreamSource所没有的方法。InputStreamSource接口,只有一个方法:

public interface InputStreamSource {

    InputStream getInputStream() throws IOException;

}

其中一些重要的方法:
getInputStream(): 找到并打开资源,返回一个InputStream以从资源中读取。预计每次调用都会返回一个新的InputStream(),调用者有责任关闭每个流
exists(): 返回一个布尔值,表明某个资源是否以物理形式存在
isOpen: 返回一个布尔值,指示此资源是否具有开放流的句柄。如果为true,InputStream就不能够多次读取,只能够读取一次并且及时关闭以避免内存泄漏。对于所有常规资源实现,返回false,但是InputStreamResource除外。
getDescription(): 返回资源的描述,用来输出错误的日志。这通常是完全限定的文件名或资源的实际URL。

其他方法:
isReadable(): 表明资源的目录读取是否通过getInputStream()进行读取。
isFile(): 表明这个资源是否代表了一个文件系统的文件。
getURL(): 返回一个URL句柄,如果资源不能够被解析为URL,将抛出IOException
getURI(): 返回一个资源的URI句柄
getFile(): 返回某个文件,如果资源不能够被解析称为绝对路径,将会抛出FileNotFoundException
lastModified(): 资源最后一次修改的时间戳
createRelative(): 创建此资源的相关资源
getFilename(): 资源的文件名是什么 例如:最后一部分的文件名 myfile.txt

8.3、Resource的实现类

Resource 接口是 Spring 资源访问策略的抽象,它本身并不提供任何资源访问实现,具体的资源访问由该接口的实现类完成——每个实现类代表一种资源访问策略。Resource一般包括这些实现类:UrlResource、ClassPathResource、FileSystemResource、ServletContextResource、InputStreamResource、ByteArrayResource

8.3.1、UrlResource访问网络资源

Resource的一个实现类,用来访问网络资源,它支持URL的绝对路径。

http:------该前缀用于访问基于HTTP协议的网络资源。
ftp:------该前缀用于访问基于FTP协议的网络资源
file: ------该前缀用于从文件系统中读取资源

1)访问基于HTTP协议的网络资源

public class UrlResourceDemo {

    public static void main(String[] args) {
        //http前缀
        loadUrlResource("http://www.baidu.com");
    }

    //访问前缀http、file
    public static void loadUrlResource(String path) {

        try {
            //创建Resource实现类的对象 UrlResource
            UrlResource url = new UrlResource(path);

            System.out.println(url.exists());

            System.out.println(url.isReadable());

            System.out.println(url.isFile());

            System.out.println(url.getURL());

            System.out.println(url.getURI());

            System.out.println(url.getFilename());

            byte[] bytes = new byte[100];
            int read = url.getInputStream().read(bytes);
            System.out.println(new String(bytes));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

2)在项目根路径下创建文件,从文件系统中读取资源

在这里插入图片描述

public class UrlResourceDemo {

    public static void main(String[] args) {
        //file前缀
        loadUrlResource("file:atguigu.txt");
    }

    //访问前缀http、file
    public static void loadUrlResource(String path) {
        try {
            //创建Resource实现类的对象 UrlResource
            UrlResource url = new UrlResource(path);

            System.out.println(url.exists());

            System.out.println(url.isReadable());

            System.out.println(url.isFile());

            System.out.println(url.getURL());

            System.out.println(url.getURI());

            System.out.println(url.getFilename());

            byte[] bytes = new byte[100];
            int read = url.getInputStream().read(bytes);
            System.out.println(new String(bytes));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

8.3.2 ClassPathResource 访问类路径下资源

ClassPathResource 用来访问类加载路径下的资源,相对于其他的 Resource 实现类,其主要优势是方便访问类加载路径里的资源,尤其对于 Web 应用,ClassPathResource 可自动搜索位于 classes 下的资源文件,无须使用绝对路径访问。

1)实验:在类路径下创建文件atguigu.txt,使用ClassPathResource 访问

//访问类路径下资源
public class ClassPathResourceDemo {

    public static void loadClasspathResource(String path) {
        //创建对象ClassPathResource
        ClassPathResource resource = new ClassPathResource(path);

        System.out.println(resource.getFilename());
        System.out.println(resource.getDescription());
        //获取文件内容
        try {
            InputStream in = resource.getInputStream();
            byte[] b = new byte[1024];
            while(in.read(b)!=-1) {
                System.out.println(new String(b));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        loadClasspathResource("atguigu.txt");
    }
}

在这里插入图片描述

8.3.3、FileSystemResource 访问文件系统资源

Spring 提供的 FileSystemResource 类用于访问文件系统资源,使用 FileSystemResource 来访问文件系统资源并没有太大的优势,因为 Java 提供的 File 类也可用于访问文件系统资源。

8.3.4、ServletContextResource

8.3.5、InputStreamResource

8.3.6、ByteArrayResource

8.4、Resource类图

在这里插入图片描述

8.5、ResourceLoader 接口

在ResourceLoader接口里有如下方法:
(1)Resource getResource(String location) : 该接口仅有这个方法,用于返回一个Resource实例。ApplicationContext实现类都实现ResourceLoader接口,因此ApplicationContext可直接获取Resource实例。

8.5.1、使用演示

实验一:ClassPathXmlApplicationContext获取Resource实例

package com.atguigu.spring6.resouceloader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class Demo1 {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext();
//        通过ApplicationContext访问资源
//        ApplicationContext实例获取Resource实例时,
//        默认采用与ApplicationContext相同的资源访问策略
        Resource res = ctx.getResource("atguigu.txt");
        System.out.println(res.getFilename());
    }
}

实验二:FileSystemApplicationContext获取Resource实例

package com.atguigu.spring6.resouceloader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.Resource;

public class Demo2 {

    public static void main(String[] args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext();
        Resource res = ctx.getResource("atguigu.txt");
        System.out.println(res.getFilename());
    }
}

8.5.3、ResourceLoader 总结

当Spring应用需要进行资源访问时,实际上并不需要直接使用Resource实现类,而是调用ResourceLoader实例的getResource()方法来获得资源,ReosurceLoader将会负责选择Reosurce实现类,也就是确定具体的资源访问策略,从而将应用程序和具体的资源访问策略分离开来


8.6、ResourceLoaderAware 接口

ResourceLoaderAware接口实现类的实例将获得一个ResourceLoader的引用,ResourceLoaderAware接口也提供了一个setResourceLoader()方法,该方法将由Spring容器负责调用,Spring容器会将一个ResourceLoader对象作为该方法的参数传入。

==具体看 Spring Bean生命周期 --> 初始化Bean 中的 —> invokeAware ==

如果把实现ResourceLoaderAware接口的Bean类部署在Spring容器中,Spring容器会将自身当成ResourceLoader作为setResourceLoader()方法的参数传入。由于ApplicationContext的实现类都实现了ResourceLoader接口,Spring容器自身完全可作为ResorceLoader使用

实验:演示ResourceLoaderAware使用

第一步 创建类,实现ResourceLoaderAware接口

package com.atguigu.spring6.resouceloader;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;

public class TestBean implements ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    //实现ResourceLoaderAware接口必须实现的方法
	//如果把该Bean部署在Spring容器中,该方法将会有Spring容器负责调用。
	//SPring容器调用该方法时,Spring会将自身作为参数传给该方法。
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    //返回ResourceLoader对象的应用
    public ResourceLoader getResourceLoader(){
        return this.resourceLoader;
    }

}

第二步 创建bean.xml文件,配置TestBean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="testBean" class="com.atguigu.spring6.resouceloader.TestBean"></bean>
</beans>

第三步 测试

package com.atguigu.spring6.resouceloader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class Demo3 {

    public static void main(String[] args) {
        //Spring容器会将一个ResourceLoader对象作为该方法的参数传入
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
        TestBean testBean = ctx.getBean("testBean",TestBean.class);
        //获取ResourceLoader对象
        ResourceLoader resourceLoader = testBean.getResourceLoader();
        System.out.println("Spring容器将自身注入到ResourceLoaderAware Bean 中 ? :" + (resourceLoader == ctx));
        //加载其他资源
        Resource resource = resourceLoader.getResource("atguigu.txt");
        System.out.println(resource.getFilename());
        System.out.println(resource.getDescription());
    }
}

8.8 应用程序上下文和资源路径

不管以怎样的方式创建ApplicationContext实例,都需要为ApplicationContext指定配置文件。

当程序创建ApplicationContext实例时,通常也是以Resource的方式来访问配置文件的,所以ApplicationContext完全支持ClassPathResource、FileSystemResource、ServletContextResource等资源访问方式。

ApplicationContext确定资源访问策略通常有两种方法:

  • (1)使用ApplicationContext实现类指定访问策略。
  • (2)使用前缀指定访问策略。

8.8.1、ApplicationContext实现类指定访问策略

创建ApplicationContext对象时,通常可以使用如下实现类:
(1) ClassPathXMLApplicationContext : 对应使用ClassPathResource进行资源访问。
(2)FileSystemXmlApplicationContext : 对应使用FileSystemResource进行资源访问。
(3)XmlWebApplicationContext : 对应使用ServletContextResource进行资源访问。

当使用ApplicationContext的不同实现类时,就意味着Spring使用相应的资源访问策略。

8.8.2、使用前缀指定访问策略

实验一:classpath前缀使用

package com.atguigu.spring6.context;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.Resource;

public class Demo1 {

    public static void main(String[] args) {
        /*
         * 通过搜索文件系统路径下的xml文件创建ApplicationContext,
         * 但通过指定classpath:前缀强制搜索类加载路径
         * classpath:bean.xml
         * */
        ApplicationContext ctx =
                new ClassPathXmlApplicationContext("classpath:bean.xml");
        System.out.println(ctx);
        Resource resource = ctx.getResource("atguigu.txt");
        System.out.println(resource.getFilename());
        System.out.println(resource.getDescription());
    }
}

实验二:classpath通配符使用

classpath * :前缀提供了加载多个XML配置文件的能力,当使用classpath*:前缀来指定XML配置文件时,系统将搜索类加载路径,找到所有与文件名匹配的文件,分别加载文件中的配置定义,最后合并成一个ApplicationContext。

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:bean.xml");
System.out.println(ctx);

当使用classpath * :前缀时,Spring将会搜索类加载路径下所有满足该规则的配置文件。
如果不是采用classpath * :前缀,而是改为使用classpath:前缀,Spring则只加载第一个符合条件的XML文件

注意 :
classpath * : 前缀仅对ApplicationContext有效。实际情况是,创建ApplicationContext时,分别访问多个配置文件(通过ClassLoader的getResource方法实现)。因此,classpath * :前缀不可用于Resource。

使用三:通配符其他使用

一次性加载多个配置文件的方式:指定配置文件时使用通配符

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:bean*.xml");

Spring允许将classpath*:前缀和通配符结合使用:

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:bean*.xml");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值