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

Spring Boot 1.5.14启动报错:PlainTextInputStream无法转为JarFile

问题分析与解决方案

报错原因

这段代码的核心问题是默认假设当前类一定从Jar包加载,但本地开发时(比如IDE直接运行),类通常是从文件系统的target/classes目录(解压状态)加载的。此时getClass().getProtectionDomain().getCodeSource().getLocation()返回file协议的URL,调用getContent()会返回目录内容的PlainTextInputStream,强转JarFile必然抛出类型转换异常。

修复方案

修改代码,先判断运行环境的资源协议,分别处理Jar包和文件系统两种场景:

@PostConstruct
public void onPostConstruct() throws IOException {
    URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
    String protocol = location.getProtocol();
    
    if ("jar".equals(protocol)) {
        // 处理Jar包运行场景
        JarURLConnection jarConnection = (JarURLConnection) location.openConnection();
        JarFile jarFile = jarConnection.getJarFile();
        // 这里添加你原本对jarFile的操作逻辑
    } else if ("file".equals(protocol)) {
        // 处理本地开发(文件系统)场景
        File resourceDir = new File(location.toURI());
        // 根据业务需求遍历目录或读取资源,比如直接从resourceDir下查找目标文件
    } else {
        throw new IOException("不支持的资源协议: " + protocol);
    }
}

额外说明

Spring Boot 1.5.x在IDE中默认以解压模式运行项目,类文件直接从编译后的目录加载,而非打包成Jar。只有执行mvn package后运行生成的Jar包时,才会触发Jar协议的处理分支。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:12:44