17370845950

如何在 Spring Boot 中正确读取配置目录下的 PEM 文件内容

本文介绍在 spring boot 应用中,通过 `spring.config.additional-location` 指定外部配置目录后,如何安全、可移植地读取其中非属性类文件(如 `test.pem`)的内容为字符串,避免硬编码绝对路径或触发 `nosuchfileexception`。

Spring Boot 的 -Dspring.config.additional-location 参数仅用于加载配置资源(如 application.yml、application.properties 等),它会由 Spring 的 ConfigDataLocationResolver 解析并注入到环境(Environment)中。而 .pem 文件属于二进制/文本资源文件,不被 Spring 配置机制自动识别或注册为可注入 Bean,因此无法通过 @Value("${...}") 或 @ConfigurationProperties 直接读取其内容——这也是你调用 Files.readAllBytes(Paths.get("test.pem")) 报 NoSuchFileException 的根本原因:JVM 当前工作目录(user.dir)通常为项目根目录或 IDE 启动路径,并非你指定的 rdk-factory-data-config/ 目录。

✅ 正确方案:通过配置驱动 + 资源定位读取 PEM 文件

步骤 1:在配置文件中声明 PEM 文件路径(推荐使用相对路径)

在你的外部配置目录(如 /Users/bharatsuthar/.../rdk-factory-data-config/)下,确保存在 application.yml(或 application-local.yml),并添加如下配置:

# rdk-factory-data-config/application-local.yml
app:
  cert:
    pem-path: test.pem  # 相对于 spring.config.additional-location 指定的目录
? 提示:该路径是相对于 -Dspring.config.additional-location 所指定的目录(即 rdk-factory-data-config/),因此 test.pem 即表示该目录下的同名文件。

步骤 2:在 Java 代码中注入路径并安全读取文件

使用 @Value 获取配置值,并结合 ResourceLoader 定位并读取文件(强烈推荐此方式,支持 classpath 和 file: 协议,且可跨环境运行):

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class PemReaderService {

    private final ResourceLoader resourceLoader;
    private final String pemPath;

    public PemReaderService(ResourceLoader resourceLoader,
                            @Value("${app.cert.pem-path}") String pemPath) {
        this.resourceLoader = resourceLoader;
        this.pemPath = pemPath;
    }

    /**
     * 从配置目录读取 PEM 文件内容为字符串(UTF-8 编码)
     * 支持 file:/xxx/ 格式路径(需以 file: 开头)或纯文件名(默认视为 relative to additional-location)
     */
    public String readPemAsString() throws IOException {
        // 构造 file: URL:指向 spring.config.additional-location 目录下的 pem 文件
        String fileUrl = "file:" + System.getProperty("spring.config.additional-location", "")
                .replace("file:", "") // 移除可能存在的 file: 前缀(避免重复)
                .trim()
                .replaceAll("/$", "") // 去除末尾斜杠
                + "/" + pemPath;

        Resource resource = resourceLoader.getResource(fileUrl);
        if (!resource.exists()) {
            throw new IllegalStateException("PEM file not found at: " + fileUrl);
        }

        return new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
    }
}

✅ 替代方案(更简洁,适用于确定为本地文件系统)

若你明确所有环境均使用 file: 协议加载配置目录,也可直接拼接 Paths(注意:必须确保 spring.config.additional-location 以 file: 开头):

import java.nio.file.Files;
import java.nio.file.Paths;

public String readPemDirectly() throws IOException {
    String baseDir = System.getProperty("spring.config.additional-location");
    if (baseDir == null || !baseDir.startsWith("file:")) {
        throw new IllegalStateException("spring.config.additional-location must be a file:// URL");
    }
    String resolvedPath = baseDir.replace("file:", "") + "/" + pemPath;
    return Files.readString(Paths.get(resolvedPath), StandardCharsets.UTF_8);
}

⚠️ 注意事项:

  • 不要使用 Paths.get("test.pem") —— 这依赖当前工作目录(user.dir),不可靠;
  • spring.config.additional-location 的值在 JVM 启动时已固定,可通过 System.getProperty() 安全获取;
  • 使用 ResourceLoader 是 Spring 官方推荐方式,天然支持 classpath:、file:、http: 等协议,更具扩展性;
  • PEM 文件本质是 ASCII 文本,务必显式指定 StandardCharsets.UTF_8,避免平台默认编码导致乱码。

✅ 验证与使用示例

在 Controller 或启动类中调用:

@RestController
public class CertController {

    private final PemReaderService pemReaderService;

    public CertController(PemReaderService pemReaderService) {
        this.pemReaderService = pemReaderService;
    }

    @GetMapping("/cert")
    public String getCert() {
        try {
            return pemReaderService.readPemAsString();
        } catch (IOException e) {
            throw new RuntimeException("Failed to load PEM certificate", e);
        }
    }
}

启动命令保持不变(确保 spring.config.additional-location 指向含 test.pem 和 application.yml 的目录):

java -Dspring.profiles.active=local \
     -Dspring.config.additional-location=file:/Users/bharatsuthar/HGW/codebaseDevelopmentRepo1/data-generation-tool/rdk-factory-data-config/ \
     -jar your-app.jar

✅ 此方案完全解耦路径硬编码,适配开发、测试、CI 环境,且符合 Spring Boot 外部化配置最佳实践。