Spring Boot 中使用 ResourceLoader 加载资源的完整示例

ResourceLoader 是 Spring 框架中用于加载资源的接口。它定义了一系列用于获取资源的方法,可以处理各种资源,包括类路径资源、文件系统资源、URL 资源等。

以下是 ResourceLoader 接口的主要方法:

  1. Resource getResource(String location)

    • 根据给定的资源位置字符串返回一个 Resource 对象。
    • 位置字符串可以是类路径、文件系统路径、URL 等形式。
  2. ClassLoader getClassLoader()

    • 返回与此资源加载器关联的类加载器。
    • 可以用于加载类路径下的资源。
  3. Resource[] getResources(String locationPattern)

    • 根据模式字符串返回一个资源数组。
    • 模式字符串支持通配符,比如 classpath*:/**/*.xml
  4. Class<?> resolveClassName(String className)

    • 根据类名解析成 Class 对象。
    • 这样可以方便地获取到类信息。

在 Spring 框架中,ResourceLoader 的常用实现类是 DefaultResourceLoader,它提供了对资源加载的默认实现。在大多数情况下,不需要手动实现这个接口,而是使用 Spring 框架中提供的资源加载机制。

在 Spring Boot 中,ResourceLoader 的默认实现是 ResourceLoader 接口的实现类 DefaultResourceLoader。Spring Boot 还提供了更高级的资源加载方式,例如使用 @Value 注解加载配置文件中的属性,或者使用 @PropertySource 注解加载外部配置文件。

要使用 ResourceLoader,可以将其注入类中,例如在 Spring Boot 的组件中:

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class MyResourceLoader {

    @Autowired
    private ResourceLoader resourceLoader;

    public void loadResource(String location) {
        Resource resource = resourceLoader.getResource(location);

        // 处理资源,例如读取文件内容
        // ...
    }
}

在上面的例子中,ResourceLoader 被注入到 MyResourceLoader 中,可以使用它来加载资源。

下面来一个完整的例子:

1、创建一个demo.txt用来测试

resources/demo.txt

复制代码
这是一个测试文本第一行
这是一个测试文本第二行
这是一个测试文本第三行

2、定义资源加载解析组件

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class MyResourceLoader {

    @Autowired
    private ResourceLoader resourceLoader;

    public String loadResource(String location) {
        // 获取资源
        Resource resource = resourceLoader.getResource(location);

        // 检查资源是否存在
        if (!resource.exists()) {
            System.out.println("该资源不存在!");
            return "该资源不存在!";
        }

        System.out.println("资源存在!");

        try (InputStream inputStream = resource.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
             StringWriter writer = new StringWriter()) {

            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                // 添加换行符 :每次读取一行后都会添加一个换行符,确保了每行的结尾都有换行符。
                // 如果仍然没有效果,请确认文件本身是否包含换行符。
                writer.write(System.lineSeparator());
            }

            return writer.toString();
        } catch (IOException e) {
            System.err.println("读取资源错误: " + e.getMessage());
            return "读取资源错误: " + e.getMessage();
        }
    }
}

3、service

复制代码
import com.lfsun.demolfsunstudyresourceloader.config.MyResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ResourceService {

    @Autowired
    private MyResourceLoader resourceLoader;

    public String getMyResource(String fileName) {
        System.out.println("寻找资源:" + String.format("classpath:%s",fileName));
        return resourceLoader.loadResource(String.format("classpath:%s",fileName));
    }

}

4、controller

复制代码
import com.lfsun.demolfsunstudyresourceloader.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    // http://localhost:8080/resource/demo.txt
    @GetMapping("/{fileName}")
    public String getMyResource(@PathVariable String fileName) {
        return resourceService.getMyResource(fileName);
    }
}

5、访问 http://localhost:8080/resource/demo.txt 即可

Edge:加了换行还是没效果...Google也是

Apifox 正常:

相关推荐
彭于晏Yan6 分钟前
Maven 资源插件:非过滤文件后缀配置及风险规避
java·spring boot·maven
benpaodeDD7 分钟前
idea里创建maven的web项目
java
青衫码上行7 分钟前
如何接入AI大模型
java·人工智能·ai·langchain·ai编程
摇滚侠8 分钟前
并发编程 Java 面试题 真正的 offer 偏方 Java 基础 Java 高级
java·开发语言
兰令水9 分钟前
topcode【随机算法题】【2026.5.15打卡-java版本】
java·算法·leetcode
Ting-yu15 分钟前
SpringCloud快速入门(10)---- Sentinel(应用场景&控制台安装)
spring·spring cloud·sentinel
JAVA学习通2 小时前
北京明光云振铎数据科技Java面经
java·开发语言·科技
贫民窟的勇敢爷们8 小时前
SpringBoot整合AOP切面编程实战,实现日志统一记录+接口权限校验
java·spring boot·spring
AC赳赳老秦9 小时前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
迈巴赫车主9 小时前
Java基础:list、set、map一遍过
java·开发语言