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

Docker部署Spring Boot War包无法加载资源文件问题排查

问题根源

你遇到的问题核心是资源读取方式错误:

  • 在IntelliJ本地运行时,项目资源会被解压到本地文件系统,getResource("binFolder").getFile()能拿到真实的文件夹路径,FileInputStream可以正常读取文件。
  • 但打包成WAR部署到Docker后,所有classpath资源都被封装在WAR归档文件内部,getResource("binFolder").getFile()返回的是类似jar:file:/app/services.war!/WEB-INF/classes/binFolder的特殊URL路径,这不是文件系统中的真实路径,FileInputStream无法识别并访问,最终抛出空指针异常。
解决思路

直接通过类加载器的getResourceAsStream()方法读取资源,该方法可以直接从classpath(包括归档文件内部)获取输入流,无需依赖文件系统路径。

修改后的BinLoader代码:

public class BinLoader {
    public static String[] loadBinFile() throws IOException {
        // 直接读取classpath中的目标文件输入流
        try (InputStream inputStream = BinLoader.class.getClassLoader().getResourceAsStream("binFolder/my-bin-file.bin")) {
            if (inputStream == null) {
                throw new FileNotFoundException("未在classpath中找到my-bin-file.bin文件");
            }
            // 构建模型的逻辑
            ...
        }
    }
}
额外验证步骤
  1. 确认WAR包中包含目标文件:在本地执行jar tf target/services-*.war,检查输出中是否存在WEB-INF/classes/binFolder/my-bin-file.bin。
  2. 调试路径问题:可以在代码中添加日志打印BinLoader.class.getClassLoader().getResource("binFolder/my-bin-file.bin")的返回值,在Docker环境下运行时,会看到该URL指向WAR内部的资源路径,而非文件系统路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:10:04