【Spring】资源操作管理:Resource、ResourceLoader、ResourceLoaderAware;

news2024/9/20 5:28:53

在这里插入图片描述

个人简介:Java领域新星创作者;阿里云技术博主、星级博主、专家博主;正在Java学习的路上摸爬滚打,记录学习的过程~
个人主页:.29.的博客
学习社区:进去逛一逛~

在这里插入图片描述

资源操作:Spring Resources

  • 一、Resource接口
    • 🚀 Resource接口实现类:
      • ⚪UrlResource
      • ⚪ClassPathResource
      • ⚪FileSystemResource
      • ⚪ServletContextResource
      • ⚪InputStreamResource
      • ⚪ByteArrayResource
  • 二、ResourceLoader 接口
  • 三、ResourceLoaderAware接口
  • 四、让Spring为Bean实例依赖注入资源(建议)



一、Resource接口


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

public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isReadable();

    boolean isOpen();

    boolean isFile();

    URL getURL() throws IOException;

    URI getURI() throws IOException;

    File getFile() throws IOException;

    ReadableByteChannel readableChannel() throws IOException;

    long contentLength() throws IOException;

    long lastModified() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();
}

其中一些重要的方法:

  • 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


🚀 Resource接口实现类:


在这里插入图片描述


⚪UrlResource

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

http:------该前缀用于访问基于HTTP协议的网络资源。

ftp:------该前缀用于访问基于FTP协议的网络资源

file: ------该前缀用于从文件系统中读取资源

案例:

import org.springframework.core.io.UrlResource;
import java.io.IOException;
import java.net.MalformedURLException;

/**
 * @author .29.
 * @create 2023-03-01 9:11
 */
public class urlResources {
    public static void loadAndReadUrlResources(String path){
        UrlResource url = null;

        try {
            url = new UrlResource(path);
            //获取资源名
            System.out.println(url.getURL());
            System.out.println(url.getFilename());
            //获取资源描述
            System.out.println(url.getDescription());
            //获取资源内容
            System.out.println(url.getInputStream().read());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        //访问网络资源,测试UrlResource功能
//        loadAndReadUrlResources("http://www.baidu.com");

        //方法二:读取文件获取路径
        loadAndReadUrlResources("file:baidu.txt");
    }
}
注意:file:前缀,读取的是根路径下的类容!

http:前缀测试结果:
在这里插入图片描述
file:前缀测试结果:
在这里插入图片描述



⚪ClassPathResource

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

案例

import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author .29.
 * @create 2023-03-02 20:20
 */

//测试ClassPathResource();
public class ClassPathResourceDemo {
    public static void main(String[] args){
        loadClassPathResource("baidu.txt");
    }
    public static void loadClassPathResource(String path){
        ClassPathResource resource = new ClassPathResource(path);

        //获取文件信息
        System.out.println(resource.getFilename());
        System.out.println(resource.getDescription());

        //获取文件内容
        try {
            InputStream inputStream = resource.getInputStream();
            byte[] bytes = new byte[1024];
            if(inputStream.read(bytes) != -1){
                System.out.println(new String(bytes));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

在这里插入图片描述



⚪FileSystemResource

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

案例

import org.springframework.core.io.FileSystemResource;

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

/**
 * @author .29.
 * @create 2023-03-02 20:32
 */
public class FileSystemResourceDemo {
    public static void main(String[] args){
        loadFileSystemResource("d:\\haojin.txt"); //path是绝对路径
    }
    public static void loadFileSystemResource(String path){
        FileSystemResource fileSystemResource = new FileSystemResource(path);
        //获取系统资源的信息
        System.out.println(fileSystemResource.getFilename());
        System.out.println(fileSystemResource.getDescription());

        //获取资源内容
        try {
            InputStream inputStream = fileSystemResource.getInputStream();
            byte[] bytes = new byte[1024];
            if(inputStream.read(bytes) != 1){
                System.out.println(new String(bytes));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述



⚪ServletContextResource

这是ServletContext资源的Resource实现,它解释相关Web应用程序根目录中的相对路径。它始终支持流(stream)访问和URL访问,但只有在扩展Web应用程序存档且资源实际位于文件系统上时才允许java.io.File访问。无论它是在文件系统上扩展还是直接从JAR或其他地方(如数据库)访问,实际上都依赖于Servlet容器。

⚪InputStreamResource

InputStreamResource 是给定的输入流(InputStream)的Resource实现。它的使用场景在没有特定的资源实现的时候使用(感觉和@Component 的适用场景很相似)。与其他Resource实现相比,这是已打开资源的描述符。 因此,它的isOpen()方法返回true。如果需要将资源描述符保留在某处或者需要多次读取流,请不要使用它。

⚪ByteArrayResource

字节数组的Resource实现类。通过给定的数组创建了一个ByteArrayInputStream。它对于从任何给定的字节数组加载内容非常有用,而无需求助于单次使用的InputStreamResource。



二、ResourceLoader 接口


Spring将采用和ApplicationContext相同的策略来访问资源。也就是说,如果ApplicationContext是FileSystemXmlApplicationContext,res就是FileSystemResource实例;如果ApplicationContext是ClassPathXmlApplicationContext,res就是ClassPathResource实例

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

案例

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

/**
 * @author .29.
 * @create 2023-03-02 20:53
 */
public class ResourceLoaderDemo {
    public static void main(String[] args){
        //示例一:
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
        Resource resource = context.getResource("baidu.txt");
        System.out.println(resource.getFilename());
        System.out.println(resource.getDescription());

        System.out.println("----------------------------------------------------------");

        //示例二:
        FileSystemXmlApplicationContext context2 = new FileSystemXmlApplicationContext();
        Resource resource2 = context.getResource("baidu.txt");
        System.out.println(resource2.getFilename());
        System.out.println(resource2.getDescription());
    }
}



三、ResourceLoaderAware接口


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

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

案例
1.创建接口实现类:

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

/**
 * @author .29.
 * @create 2023-03-02 21:08
 */
public class testBean implements ResourceLoaderAware {

    private ResourceLoader resourceLoader;

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

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

2.配置实现类的bean:

<?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.haojin.spring.resources.ResourceLoaderAwareDemo.testBean"></bean>

</beans>

3.测试:

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


/**
 * @author .29.
 * @create 2023-03-02 21:12
 */
public class Demo {
    public static void main(String[] args){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        testBean testBean = context.getBean("testBean", testBean.class);
        ResourceLoader resourceLoader = testBean.getResourceLoader();
        System.out.println("Spring容器将自身注入到ResourceLoaderAware Bean 中:" + (context == resourceLoader));
    }
}

在这里插入图片描述



四、让Spring为Bean实例依赖注入资源(建议)


当程序获取 Resource 实例时,总需要提供 Resource 所在的位置,不管通过 FileSystemResource 创建实例,还是通过 ClassPathResource 创建实例,或者通过 ApplicationContext 的 getResource() 方法获取实例,都需要提供资源位置。这意味着:资源所在的物理位置将被耦合到代码中,如果资源位置发生改变,则必须改写程序。因此,通常建议采用依赖注入,让 Spring 为 Bean 实例依赖注入资源。

案例
1.创建依赖注入类,定义属性和方法:

import org.springframework.core.io.Resource;

/**
 * @author .29.
 * @create 2023-03-02 21:36
 */
public class ResourceBean {
    //Resource实现类对象
    private Resource resource;

    //对象的Getter() 和 Setter()
    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    //输出资源信息的方法
    public void parse(){
        System.out.println(resource.getDescription());
        System.out.println(resource.getFilename());
    }
}

2.创建spring配置文件,配置依赖注入:

利用依赖注入,以后只需要在配置文件中修改资源文件位置即可
<?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 = "resourceBean" class="com.haojin.spring.resources.DI.ResourceBean">
        <property name="resource" value="baidu.txt"/>
    </bean>
    
</beans>

3.测试:

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author .29.
 * @create 2023-03-02 21:38
 */
public class testDI {
    public static void main(String[] args){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        ResourceBean resourceBean = context.getBean("resourceBean", ResourceBean.class);
        resourceBean.parse();
    }
}

在这里插入图片描述



在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/393459.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

智能家居创意产品一Homkit智能通断器

智能通断器&#xff0c;也叫开关模块&#xff0c;可以非常方便地接入家中原有开关、插座、灯具、电器的线路中&#xff0c;通过手机App或者语音即可控制电路通断&#xff0c;轻松实现原有家居设备的智能化改造。 随着智能家居概念的普及&#xff0c;越来越多的人想将自己的家改…

Pytest自动化测试框架-权威教程06-使用Marks标记测试用例

使用Marks标记测试用例通过使用pytest.mark你可以轻松地在测试用例上设置元数据。例如, 一些常用的内置标记&#xff1a;skip - 始终跳过该测试用例skipif - 遇到特定情况跳过该测试用例xfail - 遇到特定情况,产生一个“期望失败”输出parametrize - 在同一个测试用例上运行多次…

自旋锁,读写锁以及他们的异同

自旋锁 自旋锁是一种用于多线程编程的同步机制。它是一种基于忙等待的锁&#xff0c;当线程尝试获取锁时&#xff0c;如果锁已被其他线程占用&#xff0c;则该线程会一直循环检查锁是否被释放&#xff0c;直到获取到锁为止。 在自旋锁的实现中&#xff0c;使用了CPU的硬件特性…

ArcGIS制图之阴影效果的表达与运用

一、运用制图表达进行投影表达 在专题图的制作过程中&#xff0c;经常需要将目标区域从底图中进行突显&#xff0c;运用制图表达制作图层投影可以较好地实现这一目的。具体步骤如下&#xff1a; 1.将目标图层存储于数据库中并加载至窗口&#xff08;shapefile格式数据无法支持…

Android Looper简介

本文基于安卓11。 Looper是一个用具&#xff0c;在安卓程序中&#xff0c;UI线程是由事件驱动的&#xff08;onCreate, onResume, onDestory&#xff09;&#xff0c;Looper就是处理这些事件的工具&#xff0c;事件被描述为消息&#xff08;Message&#xff09;&#xff0c;Lo…

【PHP代码注入】PHP代码注入漏洞

漏洞原理RCE为两种漏洞的缩写&#xff0c;分别为Remote Command/Code Execute&#xff0c;远程命令/代码执行PHP代码注入也叫PHP代码执行(Code Execute)(Web方面)&#xff0c;是指应用程序过滤不严&#xff0c;用户可以通过HTTP请求将代码注入到应用中执行。代码注入(代码执行)…

python甜橙歌曲音乐网站平台源码

wx供重浩&#xff1a;创享日记 对话框发送&#xff1a;python音乐 获取完整源码源文件说明文档配置教程等 在虚拟环境下输入命令“python manage.py runserver”启动项目&#xff0c;启动成功后&#xff0c;访问“http://127.0.0.1:5000”进入甜橙音乐网首页&#xff0c;如图1所…

YOLOS调试记录

YOLOS是由华中科大提出的将Transformer迁移到计算机视觉领域的目标检测方法&#xff0c;其直接魔改ViT&#xff01;本文首次证明&#xff0c;通过将一系列固定大小的非重叠图像块作为输入&#xff0c;可以以纯序列到序列的方式实现2D目标检测。 模型结构 下面来调试一下该项目…

【微信小程序】-- 页面事件 - 上拉触底 - 案例(二十七)

&#x1f48c; 所属专栏&#xff1a;【微信小程序开发教程】 &#x1f600; 作  者&#xff1a;我是夜阑的狗&#x1f436; &#x1f680; 个人简介&#xff1a;一个正在努力学技术的CV工程师&#xff0c;专注基础和实战分享 &#xff0c;欢迎咨询&#xff01; &…

javaScript基础面试题 ---对象考点

1、对象是通过new操作符构建出来的&#xff0c;所以对象之间不相等 2、对象注意引用类型&#xff0c;如果是引用类型&#xff0c;就可能会相等 3、现在对象本身查找 -> 构造函数中找 -> 对象原型中找 -> 构造函数原型中找 -> 对象上一层原型… 1、对象是通过new操作…

被骗进一个很隐蔽的外包公司,入职一个月才发现,已经有了社保记录,简历污了,以后面试有影响吗?...

职场的套路防不胜防&#xff0c;一不留神就会掉坑&#xff0c;一位网友就被“骗”进了外包公司&#xff0c;他说公司非常隐蔽&#xff0c;入职一个月才发现是外包&#xff0c;但已经有了社保记录&#xff0c;简历污了&#xff0c;不知道对以后面试有影响吗&#xff1f;楼主说&a…

Mysql迁移Postgresql

目录原理环境准备操作系统(Centos7)Mysql客户端安装Psql客户端安装数据库用户导表脚本dbmysql2pgmysqlcopy测试在mysql中建表导表测试查看pg中的表原理 Mysql抽取&#xff1a;mysql命令重定向到操作系统文件&#xff0c;处理成csv文件&#xff1b; PG装载&#xff1a;copy方式…

【大数据源码】Hadoop源码解读 Namenode 启动加载FsImage的过程

Namenode 启动前言启动 Namenode 组件启动脚本Namenode.initializeFSNamesystem.loadFromDiskFsImage.recoverTransitionReadFSImageFormat.loadFSImageFormatProtobuf.load反序列化加载FsImage文件内容FsImage内存数据结构前言 NameNode是HDFS中负责元数据管理的组件&#xf…

PhpStudy下载安装使用教程,图文教程(超详细)

「作者简介」&#xff1a;CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者 「推荐专栏」&#xff1a;对网络安全感兴趣的小伙伴可以关注专栏《网络安全入门到精通》 PhpStudy一、官网下载二、安装三、简单使用四、粉丝福利PhpStudy&#xff1a;让天下没有难…

bable和AST概述

这里写目录标题bable定义Babel概述Babel 中重要的对象VistorAST定义Javascript 语法的AST&#xff08;抽象语法树&#xff09;bable 定义 Babel 是我们知道的将 ES6、ES7等代码转译为 ES5 代码且能安全稳定运行最好的工具同时它允许开发者开发插件&#xff0c;能够在编译时期…

关于 interface{} 会有啥注意事项?上

学习 golang &#xff0c;对于 interface{} 接口类型&#xff0c;我们一定绕不过&#xff0c;咱们一起来看看 使用 interface{} 的时候&#xff0c;都有哪些注意事项吧 interface {} 可以用于模拟多态 xdm 咱们写一个简单的例子&#xff0c;就举动物的例子 写一个 Animal 的…

【LeetCode】剑指 Offer(17)

目录 题目&#xff1a;剑指 Offer 34. 二叉树中和为某一值的路径 - 力扣&#xff08;Leetcode&#xff09; 题目的接口&#xff1a; 解题思路&#xff1a; 代码&#xff1a; 过啦&#xff01;&#xff01;&#xff01; 写在最后&#xff1a; 题目&#xff1a;剑指 Offer …

Spring Cache简单介绍和使用

目录 一、简介 二、使用默认ConcurrentMapManager &#xff08;一&#xff09;创建数据库和表 &#xff08;二&#xff09;创建boot项目 &#xff08;三&#xff09;使用Api 1、EnableCaching 2、CachePut 3、cacheable 4、CacheEvict 三、使用redis作为cache 一、简…

云计算基础——云计算认知

云计算的总体框架在服务方面&#xff0c;主要以提供用户基于云的各种服务为主&#xff0c;共包含3个层次:1.软件即服务&#xff08;Software as a Service&#xff0c;简称SaaS)&#xff0c;这层的作用是将应用主要以基于Web 的方式提供给客户;2.平台即服务(Platform as a Serv…

STL讲解——模拟实现vector

STL讲解——模拟实现vector vector深度剖析 在STL源码中&#xff0c;发现vector定义的并不是 start、size、capacity&#xff0c;而是start、finish、end_of_storage. 这样就可以得到size()和capacity()。 sizefinish-start capacityend_of_storage-start 扩容可能是本地扩容也…