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

Spring Boot项目中将CHANGELOG文件添加到类路径的方案咨询

Spring Boot 读取类路径下CHANGELOG.md文件实现方案
  • 第一步:文件存放与命名校准
    首先将CHANGELOG.md文件放在项目src/main/resources目录下,注意文件名大小写要和代码中声明的一致,避免Linux环境下大小写敏感导致读取失败。如果你代码里写的是"CHANGELOG.MD",要么将文件重命名为全大写,要么将代码调整为和实际文件名一致,例如new ClassPathResource("CHANGELOG.md")。
  • 第二步:编写端点读取逻辑
    直接在Controller中实现读取逻辑即可,示例代码如下:
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@RestController
public class ChangelogController {

    @GetMapping("/changelog")
    public String getChangelog() throws Exception {
        ClassPathResource myChangeLogFile = new ClassPathResource("CHANGELOG.md");
        // 显式指定UTF-8编码读取,避免中文乱码
        try (InputStreamReader reader = new InputStreamReader(myChangeLogFile.getInputStream(), StandardCharsets.UTF_8)) {
            return FileCopyUtils.copyToString(reader);
        }
    }
}
  • 第三步:打包配置校验(可选,防止打包时文件丢失)
    如果你使用Maven打包,需要确认pom.xml的资源规则没有排除md文件,如果有自定义资源过滤规则,需要加入md文件的包含配置,示例如下:
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.yml</include>
                <include>**/*.yaml</include>
                <include>**/*.properties</include>
                <include>**/*.md</include> <!-- 新增md文件包含规则 -->
            </includes>
            <filtering>false</filtering> <!-- 关闭md文件的资源过滤,避免内容中的占位符被误替换 -->
        </resource>
    </resources>
</build>

注意:如果开启了资源过滤(filtering=true),CHANGELOG文件内如果有${xxx}格式的内容会被Maven自动替换,所以建议针对md文件单独关闭过滤。

  • 常见问题排查
    • 抛出FileNotFoundException:先检查项目打包后的target/classes目录下是否存在CHANGELOG.md文件,再核对文件名大小写是否和代码中声明的完全一致
    • 内容中文乱码:确认读取时指定了UTF-8编码,同时CHANGELOG文件本身的保存格式为UTF-8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:00:00