You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何从配置目录读取test.pem为字符串(无需绝对路径)

解决Spring Boot从指定额外配置目录读取test.pem文件的问题

问题原因

直接使用Paths.get("test.pem")会从JVM当前工作目录查找文件,而非你通过-Dspring.config.additional-location指定的额外配置目录,因此抛出NoSuchFileException。

解决方案

以下几种方式可无需硬编码绝对路径,从指定配置目录读取文件:

方法1:使用Spring的ResourceLoader(推荐)

Spring Boot会自动将spring.config.additional-location指定的目录纳入资源搜索路径,通过ResourceLoader可直接加载该目录下的文件:

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;

@Component
public class PemFileLoader {

    private final ResourceLoader resourceLoader;

    // 构造函数注入ResourceLoader
    public PemFileLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public String loadTestPem() throws IOException {
        // 直接加载配置目录下的test.pem
        Resource resource = resourceLoader.getResource("test.pem");
        // 读取文件内容为字符串
        return Files.readString(resource.getFile().toPath());
    }
}

方法2:通过@Value注入完整文件路径

利用@Value获取spring.config.additional-location的配置值,拼接文件名后读取:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Component
public class PemFileLoader {

    @Value("${spring.config.additional-location}test.pem")
    private Path pemFilePath;

    public String loadTestPem() throws IOException {
        return Files.readString(pemFilePath);
    }
}

注意:确保spring.config.additional-location的配置值末尾带有斜杠(如你当前配置的file:/xxx/rdk-factory-data-config/),否则需手动添加斜杠拼接路径。

方法3:使用ResourceUtils(不推荐,仅作参考)

Spring提供的ResourceUtils工具类可直接定位文件,但官方不推荐在业务代码中使用,更适合测试或工具类场景:

import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public String loadTestPem() throws IOException {
    File pemFile = ResourceUtils.getFile("test.pem");
    return Files.readString(pemFile.toPath());
}

验证说明

以上方法均无需硬编码绝对路径,依赖Spring Boot对配置目录的自动识别,符合需求。调用loadTestPem()方法即可获取test.pem的字符串内容。

内容的提问来源于stack exchange,提问作者EV Experience

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:01:15