Spring中的DefaultResourceLoader使用方法解读

 更新时间:2024年02月02日 08:45:25   作者:小徐也要努力鸭  
这篇文章主要介绍了Spring中的DefaultResourceLoader使用方法解读,DefaultResourceLoader是spring提供的一个默认的资源加载器,DefaultResourceLoader实现了ResourceLoader接口,提供了基本的资源加载能力,需要的朋友可以参考下

DefaultResourceLoader的使用

1 前言

spring的DefaultResourceLoader类实现了ResourceLoader接口,可以方便读取resources等目录下的资源文件,存在于spring-core依赖中。

其他依赖如下:

<!--    读取File转换为String  -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

2 使用

resources的Demo目录下准备测试test.json文件:

在这里插入图片描述

该包下,FileUtils.readFileToString方法可将File文件转换成String,其中需要设置字符集:

package com.xiaoxu.utils.File;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.IOException;
/**
 * @author xiaoxu
 * @date 2022-04-27
 * spring_boot:com.xiaoxu.utils.File.FileUtils
 */
public class FileUtils {
    public static String parseJsonFileToString(String caseJsonFilePath){
        DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
        Resource resource = defaultResourceLoader.getResource("classpath:" + caseJsonFilePath);
        File file;
        try {
            file = resource.getFile();
        } catch (IOException e) {
            throw new RuntimeException(String.format("调用%s方法失败,文件获取失败",
                    Thread.currentThread().getStackTrace()[1].getMethodName()));
        }
        String s;
        try {
            s = org.apache.commons.io.FileUtils.readFileToString(file, "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(String.format("调用%s方法失败,String获取失败,%s",
                    Thread.currentThread().getStackTrace()[1].getMethodName(),e.getMessage()));
        }
        return s;
    }
    public static void main(String[] args) {
        System.out.println(parseJsonFileToString("Demo/test.json"));
    }
}

执行结果如下,亦可结合fastjson使用:

{
  "data": [
    {"name": "你好","age": 30}
  ]
}

查看DefaultResourceLoader源码可知,getResource方法读取路径时,开头为classpath:的,会使用ClassPathResource类处理: 并且会截掉classpath:,

    public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        Iterator var2 = this.getProtocolResolvers().iterator();

        Resource resource;
        do {
            if (!var2.hasNext()) {
                if (location.startsWith("/")) {
                    return this.getResourceByPath(location);
                }

                if (location.startsWith("classpath:")) {
                    return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());
                }

                try {
                    URL url = new URL(location);
                    return (Resource)(ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
                } catch (MalformedURLException var5) {
                    return this.getResourceByPath(location);
                }
            }

            ProtocolResolver protocolResolver = (ProtocolResolver)var2.next();
            resource = protocolResolver.resolve(location, this);
        } while(resource == null);

        return resource;
    }

在ClassPathResource类中,还调用了Spring的工具类StringUtils的cleanPath方法将\ \换成/,还有去掉开头的/等等:

public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
    Assert.notNull(path, "Path must not be null");
    String pathToUse = StringUtils.cleanPath(path);
    if (pathToUse.startsWith("/")) {
        pathToUse = pathToUse.substring(1);
    }
    this.path = pathToUse;
    this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
}

到此这篇关于Spring中的DefaultResourceLoader使用方法解读的文章就介绍到这了,更多相关Spring的DefaultResourceLoader内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot添加License的多种方式

    SpringBoot添加License的多种方式

    License指的是版权许可证,当我们开发完系统后,如果不想让用户一直白嫖使用,比如说按时间续费,License的作用就有了。我们可以给系统指定License的有效期,控制系统的可用时间。
    2021-06-06
  • Java设计模式之中介模式

    Java设计模式之中介模式

    这篇文章主要介绍了Java设计模式之中介模式,中介模式(Mediator Pattern),属于行为型设计模式,目的是把系统中对象之间的调用关系从一对多转变成一对一的调用关系,以此来降低多个对象和类之间的通信复杂性,需要的朋友可以参考下
    2023-12-12
  • Spring Boot教程之提高开发效率必备工具lombok

    Spring Boot教程之提高开发效率必备工具lombok

    这篇文章主要介绍了Spring Boot教程之提高开发效率必备工具lombok的相关资料,需要的朋友可以参考下
    2022-08-08
  • 浅聊一下Spring Security的使用方法

    浅聊一下Spring Security的使用方法

    Spring Security 是一个基于 Spring 框架的安全框架,提供了一套安全性认证和授权的解决方案,用于保护 Web 应用程序和服务,接下来小编就和大家聊聊Spring Security,感兴趣的小伙伴跟着小编一起来看看吧
    2023-08-08
  • Java fastjson2 解析JSON用法详解

    Java fastjson2 解析JSON用法详解

    Fastjson2是Fastjson的升级版,提供了更好的性能和扩展性,它支持多种方式解析JSON数据,包括将JSON字符串转换为Java对象、嵌套的JSON对象和数组,以及转换成Map或List,本文介绍Java fastjson2 解析JSON用法,感兴趣的朋友一起看看吧
    2025-02-02
  • Java网络编程之UDP网络通信详解

    Java网络编程之UDP网络通信详解

    这篇文章主要为大家详细介绍了Java网络编程中的UDP网络通信的原理与实现,文中的示例代码讲解详细,具有一定的借鉴价值,需要的可以参考一下
    2022-09-09
  • 一文带你搞懂Java单例模式

    一文带你搞懂Java单例模式

    单例就是单实例的意思,即在系统全局,一个类只创建一个对象,并且在系统全局都可以访问这个对象而不用重新创建。本文将通过示例为大家详细讲解Java单例模式的使用,需要的可以参考一下
    2022-11-11
  • Spring Security安全框架之记住我功能

    Spring Security安全框架之记住我功能

    这篇文章主要介绍了Spring Security安全框架之记住我,本次就来探究如何实现这种自动登录、记住我的功能,通过实例代码图文相结合给大家介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • Springboot Apollo配置yml的问题及解决方案

    Springboot Apollo配置yml的问题及解决方案

    这篇文章主要介绍了Springboot Apollo配置yml的问题及解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • jpa多条件查询重写Specification的toPredicate方法

    jpa多条件查询重写Specification的toPredicate方法

    这篇文章主要介绍了多条件查询重写Specification的toPredicate方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11

最新评论