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

SpringBoot打包jar在Linux/Windows非IDE启动无法访问公共资源

问题根因

从异常栈java.net.UnknownHostException: var以及FTP协议调用日志可以明确判断:你的静态资源路径拼接规则错误,导致Spring将本地文件路径识别为FTP远程地址,触发域名解析失败报错。
具体来说:Linux系统下文件绝对路径以/开头(比如上传目录的绝对路径是/var/app/docs),你原有代码中拼接file:/ + 绝对路径后,得到的地址是file://var/app/docs,Spring会将第二个/后的var识别为远程主机地址,尝试走FTP协议访问,自然报错。Windows下IDE运行正常是因为Windows路径开头是盘符(比如C:\xxx),拼接后没有该歧义。

修复方案

修改MvcConfig中的资源路径拼接逻辑,调整本地文件协议的前缀即可:

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        exposeDirectory("docs", registry);
    }
    
    private void exposeDirectory(String dirName, ResourceHandlerRegistry registry) {
        Path uploadDir = Paths.get(dirName);
        String uploadPath = uploadDir.toFile().getAbsolutePath();
        
        if (dirName.startsWith("../")) dirName = dirName.replace("../", "");
        
        registry
                .addResourceHandler("/" + dirName + "/**")
                // 原错误代码:.addResourceLocations("file:/"+ uploadPath + "/");
                // 修改为以下任意一种都可适配全平台
                .addResourceLocations("file:"+ uploadPath + "/");
                // 也可以用标准本地文件协议写法:.addResourceLocations("file:///"+ uploadPath + "/");
    }
}

额外优化建议

建议将上传目录路径配置到application.yml/application.properties中,不要硬编码在代码里,避免不同运行环境路径不一致的问题,同时也方便统一管控文件存储位置,避免jar包升级覆盖上传的文件:

# application.yml 配置示例
upload:
  base-path: /data/application/docs/

内容的提问来源于stack exchange,提问作者Ahmed-Makni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:39:01