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

Spring Boot嵌入式Tomcat运行外部WAR时依赖路径错误排查

问题:嵌入式Tomcat加载外部WAR时依赖路径错误

场景

原本在JBoss中运行的Spring Boot应用,切换为自带嵌入式Tomcat运行后正常,但需要加载JBoss部署目录中的另一个必需WAR文件,按方法添加后出现依赖路径错误。

错误详情

Tomcat尝试在错误路径查找依赖JAR:

Failed to scan file [c:/Users/blahblah/.m2/repository/org/glassfish/hk2/hk2/2.6.1/hk2-Utils.jar

正确路径应为:

c:/Users/blahblah/.m2/repository/org/glassfish/hk2/hk2-utils/2.6.1/hk2-utils.jar

同时asm.jar、asm-tree.jar等大量依赖也被错误定位到c:/Users/blahblah/.m2/repository/org/glassfish/hk2/hk2/2.6.1目录,手动复制JAR到错误目录也无法解决。

WAR文件内容

解压目标WAR后仅包含基础文件:

META-INF / MANIFEST.MF
WEB-INF/ web.xml, weblogic.xml
index.jsp (包含java.lang.string、java.util.*等基础导入)

解决方案

1. 检查并修正WAR的MANIFEST.MF配置

解压WAR后打开META-INF/MANIFEST.MF,查看Class-Path条目,大概率是这里的依赖路径被错误书写(比如把hk2-utils.jar写成hk2/Utils.jar),修正所有错误的依赖路径后重新打包WAR。

2. 排除Spring Boot与HK2的冲突依赖

Spring Boot嵌入式Tomcat的依赖可能和WAR隐含的HK2依赖冲突,在项目pom.xml中排除相关冲突依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.glassfish.hk2</groupId>
            <artifactId>hk2</artifactId>
        </exclusion>
        <!-- 按需添加asm等其他冲突依赖的排除规则 -->
    </exclusions>
</dependency>

3. 通过Maven正确引入WAR依赖

如果目标WAR是项目的正式依赖,直接在pom.xml中添加依赖配置,让Maven自动管理依赖路径:

<dependency>
    <groupId>WAR所属的groupId</groupId>
    <artifactId>blah</artifactId>
    <version>对应版本号</version>
    <type>war</type>
    <scope>runtime</scope>
</dependency>

4. 自定义嵌入式Tomcat类加载器

若以上方法无效,通过代码自定义Tomcat的类加载器,指定正确的依赖搜索路径:

@Bean
public TomcatServletWebServerFactory tomcatFactory() {
    return new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            WebappLoader loader = new WebappLoader(Thread.currentThread().getContextClassLoader());
            // 添加正确的依赖目录,可添加多个
            loader.addRepository("file:///c:/Users/blahblah/.m2/repository/org/glassfish/hk2/hk2-utils/2.6.1/");
            loader.addRepository("file:///c:/Users/blahblah/.m2/repository/org/asm/asm/[对应版本]/");
            context.setLoader(loader);
        }
    };
}

5. 清理Maven仓库缓存

执行Maven命令强制更新依赖,清除仓库中可能存在的损坏或路径错误的缓存:

mvn clean install -U

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 07:40:01