【第18章】spring-resource

news2025/2/28 19:55:56

文章目录

  • 前言
  • 一、Resource
    • 1.测试类
    • 2.测试结果
  • 二、ResourceLoader
    • 1.测试类
    • 2.测试结果
  • 三、ResourceLoaderAware
    • 1.实现类
    • 2.配置文件
    • 3.测试类
    • 4.测试结果
    • 5.结论
  • 总结


前言

在Spring框架中,Resource是一个关键组件,它位于org.springframework.core.io包中,用于处理资源的加载和访问。Resource接口为资源提供了一个抽象的表示,这些资源可以是文件、类路径上的资源、URL等。通过这个接口,Spring提供了一种统一的方式来加载和操作这些资源,无论它们实际上存储在哪里。

Resource接口的主要实现类包括:

ClassPathResource:表示类路径下的资源。它使用线程上下文类加载器、给定的类加载器或给定的类来加载资源。例如,你可以通过以下方式创建一个ClassPathResource对象:Resource resource = new ClassPathResource(“test.txt”);

UrlResource:表示一个URL资源。你可以通过URL字符串来创建它,例如:Resource resource = new UrlResource(“https://example.com/resource.txt”);

FileSystemResource:表示文件系统中的资源。Spring提供的这个类用于访问文件系统资源。

要使用Resource接口加载资源,首先需要获取一个ResourceLoader实例,这通常可以通过依赖注入来实现。一旦你有了ResourceLoader,你就可以使用它来加载各种资源。

Resource接口还定义了一系列方法,如exists(), isReadable(), getURL(), getFile()等,这些方法允许你查询资源的状态、获取资源的URL或文件等。

总的来说,Spring的Resource为开发者提供了一种灵活且强大的方式来处理应用程序中的资源。


一、Resource

1.测试类

package org.example.resource;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.ResourceUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Create by zjg on 2024/4/16
 */
public class ResourceTest {
    public static final String URL_PROTOCOL_HTTPS = "https";
    public static void main(String[] args) throws IOException {
        System.out.println("Hello Resource!");
        //ClassPathResource
        String path="jdbc.properties";
        loadClassPathResource(path);
        //FileSystemResource
        path="pom.xml";
        loadFileSystemResource(path);
        path="G:/workspace/spring6/pom.xml";
        loadFileSystemResource(path);
        //UrlResource
        path = "https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif";
        loadUrlResource(path);
    }
    public static void loadClassPathResource(String path) throws IOException {
        ClassPathResource resource = new ClassPathResource(path);
        load(resource);
    }
    public static void loadFileSystemResource(String path) throws IOException {
        FileSystemResource resource = new FileSystemResource(path);
        load(resource);
    }
    public static void loadUrlResource(String path) throws IOException {
        UrlResource resource = new UrlResource(path);
        load(resource);
    }
    public static void load(Resource resource) throws IOException {
        System.out.println("--------------------------------------");
        boolean exists = resource.exists();
        System.out.println(exists);
        if(exists){
            System.out.println(resource.getURL());
            String protocol = resource.getURL().getProtocol();
            System.out.println(protocol);
            System.out.println(resource.getFilename());
            System.out.println(resource.contentLength()+"字节");
            System.out.println(resource.getDescription());
            if(resource instanceof ClassPathResource){//打印类路径
                System.out.println(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).getPath());
            }
            if(ResourceUtils.URL_PROTOCOL_FILE.equals(protocol)){//打印绝对路径
                System.out.println(resource.getFile().getAbsolutePath());
            }
            if(URL_PROTOCOL_HTTPS.equals(protocol)){//下载到本地
                download(resource);
            }
        }
        System.out.println("--------------------------------------");
    }
    public static void download(Resource source) throws IOException {
        InputStream inputStream = source.getInputStream();
        //文件生成到项目根目录下
        FileOutputStream fileOutputStream = new FileOutputStream(source.getFilename());
        byte[] bytes=new byte[1024];//1kb
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,len);
        }
    }
}

2.测试结果

Hello Resource!
--------------------------------------
true
file:/G:/workspace/spring6/spring-resource/target/classes/jdbc.properties
file
jdbc.properties
234字节
class path resource [jdbc.properties]
G:\workspace\spring6\spring-resource\target\classes
G:\workspace\spring6\spring-resource\target\classes\jdbc.properties
--------------------------------------
--------------------------------------
true
file:/G:/workspace/spring6/pom.xml
file
pom.xml
2601字节
file [G:\workspace\spring6\pom.xml]
G:\workspace\spring6\pom.xml
--------------------------------------
--------------------------------------
true
file:/G:/workspace/spring6/pom.xml
file
pom.xml
2601字节
file [G:\workspace\spring6\pom.xml]
G:\workspace\spring6\pom.xml
--------------------------------------
--------------------------------------
true
https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif
https
dec4d833e4f64eb395567ac1e3746d0a.gif
18658字节
URL [https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif]
--------------------------------------

二、ResourceLoader

ResourceLoader.getResource()得到资源对象,为向上造型,实际对象为其实现类。

1.测试类

package org.example.resource.loader;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Create by zjg on 2024/4/17
 */
public class ResourceLoaderTest {
    public static final String URL_PROTOCOL_HTTPS = "https";
    public static void main(String[] args) throws IOException {
        System.out.println("Hello ResourceLoader!");
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        //加载classpath文件
        Resource resource = resourceLoader.getResource("classpath:jdbc.properties");
        load(resource);
        //加载本地文件
        resource = resourceLoader.getResource("file:pom.xml");
        load(resource);
        resource = resourceLoader.getResource("file:G:\\workspace\\spring6\\pom.xml");
        load(resource);
        //加载网络文件
        resource = resourceLoader.getResource("https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif");
        load(resource);
    }
    public static void load(Resource resource) throws IOException {
        System.out.println("--------------------------------------");
        boolean exists = resource.exists();
        System.out.println(exists);
        if(exists){
            System.out.println(resource.getURL());
            String protocol = resource.getURL().getProtocol();
            System.out.println(protocol);
            System.out.println(resource.getFilename());
            System.out.println(resource.contentLength()+"字节");
            System.out.println(resource.getDescription());
            if(resource instanceof ClassPathResource){//打印类路径
                System.out.println(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).getPath());
            }
            if(ResourceUtils.URL_PROTOCOL_FILE.equals(protocol)){//打印绝对路径
                System.out.println(resource.getFile().getAbsolutePath());
            }
            if(URL_PROTOCOL_HTTPS.equals(protocol)){//下载到本地
                download(resource);
            }
        }
        System.out.println("--------------------------------------");
    }
    public static void download(Resource source) throws IOException {
        InputStream inputStream = source.getInputStream();
        //文件生成到项目根目录下
        FileOutputStream fileOutputStream = new FileOutputStream(source.getFilename());
        byte[] bytes=new byte[1024];//1kb
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,len);
        }
    }
}

2.测试结果

Hello ResourceLoader!
--------------------------------------
true
file:/G:/workspace/spring6/spring-resource/target/classes/jdbc.properties
file
jdbc.properties
234字节
class path resource [jdbc.properties]
G:\workspace\spring6\spring-resource\target\classes
G:\workspace\spring6\spring-resource\target\classes\jdbc.properties
--------------------------------------
--------------------------------------
true
file:pom.xml
file
pom.xml
2601字节
URL [file:pom.xml]
G:\workspace\spring6\pom.xml
--------------------------------------
--------------------------------------
true
file:G:/workspace/spring6/pom.xml
file
pom.xml
2601字节
URL [file:G:/workspace/spring6/pom.xml]
G:\workspace\spring6\pom.xml
--------------------------------------
--------------------------------------
true
https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif
https
dec4d833e4f64eb395567ac1e3746d0a.gif
18658字节
URL [https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif]
--------------------------------------

三、ResourceLoaderAware

ResourceLoaderAware 接口是 Spring 框架中的一个特性,它允许 bean 在初始化时自动注入一个 ResourceLoader。ResourceLoader 是一个策略接口,用于加载类路径或文件系统上的资源。要使用 ResourceLoaderAware 接口,你需要实现该接口,并在实现中提供一个 setResourceLoader 方法,该方法将由 Spring 容器在 bean 初始化时自动调用。

上面的两种方式都是通过手动new的方式,耦合较强,未通过spring进行管理,下面我们来使用spring容器提供的回调接口来完成对资源的调用。

1.实现类

package org.example.resource.aware;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Create by zjg on 2024/4/17
 */
public class DefaultResourceLoaderAware implements ResourceLoaderAware {
    public static final String URL_PROTOCOL_HTTPS = "https";
    private ResourceLoader resourceLoader;
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader=resourceLoader;
        System.out.println("this.resourceLoader初始化完成"+this.resourceLoader);
    }

    public void getResource(String location) throws IOException {
        Resource resource = resourceLoader.getResource(location);
        System.out.println("--------------------------------------");
        boolean exists = resource.exists();
        System.out.println(exists);
        if(exists){
            System.out.println(resource.getURL());
            String protocol = resource.getURL().getProtocol();
            System.out.println(protocol);
            System.out.println(resource.getFilename());
            System.out.println(resource.contentLength()+"字节");
            System.out.println(resource.getDescription());
            if(resource instanceof ClassPathResource){//打印类路径
                System.out.println(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).getPath());
            }
            if(ResourceUtils.URL_PROTOCOL_FILE.equals(protocol)){//打印绝对路径
                System.out.println(resource.getFile().getAbsolutePath());
            }
            if(URL_PROTOCOL_HTTPS.equals(protocol)){//下载到本地
                download(resource);
            }
        }
        System.out.println("--------------------------------------");
    }
    public static void download(Resource source) throws IOException {
        InputStream inputStream = source.getInputStream();
        //文件生成到项目根目录下
        FileOutputStream fileOutputStream = new FileOutputStream(source.getFilename());
        byte[] bytes=new byte[1024];//1kb
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,len);
        }
    }
}

2.配置文件

<?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="defaultResourceLoaderAware" class="org.example.resource.aware.DefaultResourceLoaderAware"></bean>
</beans>

3.测试类

package org.example.resource.aware;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import java.io.IOException;

/**
 * Create by zjg on 2024/4/17
 */
@SpringJUnitConfig(locations = "classpath:springContext.xml")
public class ResourceLoaderAwareTest {
    @Autowired
    DefaultResourceLoaderAware resourceLoaderAware;
    @org.junit.jupiter.api.Test
    public void test() throws IOException {
        //加载classpath文件
        resourceLoaderAware.getResource("classpath:jdbc.properties");
        //加载本地文件
        resourceLoaderAware.getResource("file:pom.xml");
        resourceLoaderAware.getResource("file:G:\\workspace\\spring6\\pom.xml");
        //加载网络文件
        resourceLoaderAware.getResource("https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif");
    }
}

4.测试结果

this.resourceLoader初始化完成org.springframework.context.support.GenericApplicationContext@51549490, started on Wed Apr 17 22:25:17 CST 2024
--------------------------------------
true
file:/G:/workspace/spring6/spring-resource/target/classes/jdbc.properties
file
jdbc.properties
234字节
class path resource [jdbc.properties]
G:\workspace\spring6\spring-resource\target\classes
G:\workspace\spring6\spring-resource\target\classes\jdbc.properties
--------------------------------------
--------------------------------------
true
file:pom.xml
file
pom.xml
732字节
URL [file:pom.xml]
G:\workspace\spring6\spring-resource\pom.xml
--------------------------------------
--------------------------------------
true
file:G:/workspace/spring6/pom.xml
file
pom.xml
2601字节
URL [file:G:/workspace/spring6/pom.xml]
G:\workspace\spring6\pom.xml
--------------------------------------
--------------------------------------
true
https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif
https
dec4d833e4f64eb395567ac1e3746d0a.gif
18658字节
URL [https://img-blog.csdnimg.cn/direct/dec4d833e4f64eb395567ac1e3746d0a.gif]
--------------------------------------

5.结论

在这里插入图片描述

可以看到,spring帮我们注入了一个上下文GenericApplicationContext,这个上下文的父类实现了ResourceLoader接口,在测试类中,我们所做的只有对DefaultResourceLoaderAware的方法调用,大大减少了调用时的代码量,也不用再去new各种对象了。


总结

回到顶部

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

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

相关文章

HTML使用jQuery实现两个点击按钮,分别控制改文本字体颜色和字体大小

jQuery 简介 jQuery 是一个广泛使用的 JavaScript 库&#xff0c;旨在简化对 HTML 文档的操作、事件处理、动画效果和 AJAX 等操作。 案例源码 <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta name&q…

【Godot4自学手册】第三十八节给游戏添加音效

今天&#xff0c;我的主要任务就是给游戏添加音效。在添加音效前&#xff0c;我们需要了解一个东西&#xff1a;音频总线。这个东西或许有些枯燥&#xff0c;如果你只为添加一个音效没必要了解太多&#xff0c;但如果你以后将要经常与音频播放打交道&#xff0c;还是要了解一下…

在线测径仪的六类测头组合形式!哪种适合你?

在线测径仪&#xff0c;这一现代工业的精密仪器&#xff0c;犹如一位技艺高超的工匠&#xff0c;以其卓越的性能和精准度&#xff0c;为工业生产提供了坚实的保障。它的出现&#xff0c;不仅提高了生产效率&#xff0c;更保证了产品质量&#xff0c;为企业的可持续发展注入了强…

分析 MyBatis/MyBatis-Plus 慢 SQL 的分析组件 --SQL 慢镜️‍♀️

大家好&#xff01;我是聪ζ&#x1f331;我做了一个分析 MyBatis/MyBatis-Plus 慢 SQL 的分析组件 --SQL 慢镜&#x1f575;️‍♀️ GitHub仓库地址&#x1f680;: https://github.com/lhccong/sql-slow-mirror 点点 star 我的朋友们✨ 背景&#x1f9ca;&#xff1a; 大家…

【HarmonyOS4学习笔记】《HarmonyOS4+NEXT星河版入门到企业级实战教程》课程学习笔记(一)

课程地址&#xff1a; 黑马程序员HarmonyOS4NEXT星河版入门到企业级实战教程&#xff0c;一套精通鸿蒙应用开发 &#xff08;本篇笔记对应课程第 1 - 2节&#xff09; P1《课程介绍》 开场白&#xff0c;HarmonyOS 的一个简介&#xff0c;话不多说&#xff0c;直接看图吧&…

怎么在抖音上开店卖货?做好这些,就能轻松赚到辛苦钱!

大家好&#xff0c;我是电商花花。 抖音电商在这几年一直都非常火爆&#xff0c;不少商家和达人都在抖音上赚麻了&#xff0c;这个抖音小店项目在不断的吸引着商家入驻。 说实话&#xff0c;花花就是抖音小店的受益者&#xff0c;让当初啥也不懂的新手小白&#xff0c;到现在…

羊大师解析,夏日消暑羊奶来帮忙

羊大师解析&#xff0c;夏日消暑羊奶来帮忙 炎炎夏日&#xff0c;烈日当空&#xff0c;人们总是寻找各种方式来消暑降温。除了常见的冷饮、空调等&#xff0c;其实还有一种天然、健康的饮品可以帮助我们度过酷暑——那就是羊奶。 羊奶作为一种营养丰富的天然饮品&#xff0c;不…

【Canvas与艺术】绘制金色八卦图

【关键点】 等比例缩放各部件及将八卦转为“二进制”的过程。 【成图】 【代码】 <!DOCTYPE html> <html lang"utf-8"> <meta http-equiv"Content-Type" content"text/html; charsetutf-8"/> <head><title>使用…

加密、解密、签名、验签、数字证书、CA浅析

一、加密和解密 加密和解密应用的很广&#xff0c;主要作用就是防止数据或者明文被泄露。 加解密算法主要有两大类&#xff0c;对称加密和非对称加密。对称加密就是加密和解密的密钥都是一个&#xff0c;典型的有AES算法。非对称加密就是有公钥和私钥&#xff0c;公钥可以发布…

C++/Qt 小知识记录5

工作中遇到的一些小问题&#xff0c;总结的小知识记录&#xff1a;C/Qt 小知识5 Windows下查看端口占用情况C调用Python三方库测试库有没有被加上的测试方法初始化使用Python的env环境&#xff0c;用Py_SetPythonHome设置GDAL相关的&#xff0c;需要把osgeo、rasterio的路径加入…

Linux 操作系统的引导过程

Linux系统开机引导过程&#xff1a; 开机自检 检测硬件设备&#xff0c;找到能够引导系统的设备&#xff0c;比如硬盘MBR引导 运行MBR扇区里的主引导程序GRUB启动GRUB菜单 系统读取GRUB配置文件(/boot/grub2/grub.cfg)获取内核的设置和…

基于WOA优化的CNN-GRU-Attention的时间序列回归预测matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1卷积神经网络&#xff08;CNN&#xff09;在时间序列中的应用 4.2 GRU网络 4.3 注意力机制&#xff08;Attention&#xff09; 4.4 WOA优化算法 5.算法完整程序工程 1.算法运行效果图…

java 学习一

jdk下载地址 配置环境变量

【RAG 论文】Query2doc — 使用 LLM 做 Query Expansion 来提高信息检索能力

论文&#xff1a;Query2doc: Query Expansion with Large Language Models ⭐⭐⭐⭐⭐ Microsoft Research, EMNLP 2023 文章目录 背景介绍Query2doc 论文速读实现细节实验结果和分析总结分析 背景介绍 信息检索&#xff08;Information Retrieval&#xff0c;IR&#xff09;指…

离线数仓数据导出-hive数据同步到mysql

离线数仓数据导出-hive数据同步到mysql MySQL建库建表数据导出 为方便报表应用使用数据&#xff0c;需将ads各指标的统计结果导出到MySQL数据库中。 datax支持hive同步MySQL&#xff1a;仅仅支持hive存储的hdfs文件导出。所以reader选hdfs-reader&#xff0c;writer选mysql-wri…

新手小白能做视频号小店吗?可以,但这几点一定要搞清楚

大家好&#xff0c;我是电商笨笨熊 视频号小店的推出吸引了不少的电商玩家&#xff0c;其中也有很多新手小白&#xff0c;大家对于此项目充满好奇&#xff0c;尤其是其私域电商的模式和中年以上的未被开发的用户群体&#xff0c;处处都充满着新风口。 但正所谓拿着旧地图找不…

【好书推荐7】《机器学习平台架构实战》

【好书推荐7】《机器学习平台架构实战》 写在最前面《机器学习平台架构实战》编辑推荐内容简介作者简介目  录前  言本书读者内容介绍充分利用本书下载示例代码文件下载彩色图像本书约定 &#x1f308;你好呀&#xff01;我是 是Yu欸 &#x1f30c; 2024每日百字篆刻时光&…

ONLYOFFICE协作空间:团队高效协作的终极武器!

文章目录 ONLYOFFICE协作空间初创版专业版&#xff08;云端&#xff09;企业版&#xff08;内部部署&#xff09; 亮点功能实时多人协作编辑高效的项目管理工具无缝集成第三方存储服务安全性和合规性支持Markdown文件群组功能和存储配额管理嵌入功能和数据导入自托管协作空间支…

YOLOv8 关键点检测模型训练部署

文章目录 1、YOLOv8安装及使用1.2、命令行使用1.3、使用python-API模型预测1.4、pt转换ONNX 2、训练三角板关键点检测模型2.1、训练命令 3、ONNX Runtime部署 1、YOLOv8安装及使用 参考链接: 同济子豪兄视频 github原文链接 # 安装yolov8 pip install ultralytics --upgrade …