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

Spring Boot将依赖WAR作为独立JAR运行的报错问题求助

这种方案完全可行!你现在遇到的错误是几个关键配置和依赖没处理到位,咱们一步步来解决:

1. 先搞定嵌入式容器缺失的问题

你看到的*Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean*错误,核心原因有两个:

  • 你用的是spring-boot-starter这个基础starter,它不包含Web应用所需的自动配置逻辑,自然不会帮你创建嵌入式容器的工厂Bean
  • spring-boot-starter-tomcat的scope设成了provided,这意味着打包成可执行Jar时,Tomcat相关依赖不会被包含进去,运行时肯定找不到容器相关的类

解决方法:
把pom里的spring-boot-starter替换成专门的Web场景starter,同时调整Tomcat依赖的scope(如果不需要部署到外部Tomcat,直接去掉provided):

<dependencies>
    <!-- 替换成web starter,自动包含Tomcat、Spring MVC等Web所需组件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 嵌入式运行不需要provided,去掉这个scope -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <!-- <scope>provided</scope> -->
    </dependency>
    <!-- 其他依赖保持不变 -->
</dependencies>

2. 正确配置WAR包依赖

你把WAR作为依赖引入,但Maven默认只会处理Jar类型的依赖,所以必须显式指定依赖类型为war,这样Maven才会把WAR里的类、资源都加载到项目的classpath中:

<dependency>
    <groupId>com.other.app</groupId>
    <artifactId>CoolWARApplication</artifactId>
    <version>${app.version}</version>
    <type>war</type>
</dependency>

3. 确保原WebMVC项目的Bean被扫描到

你的@SpringBootApplication默认只会扫描demo.demo包及其子包的组件,而原WAR项目的Controller、Service等类肯定在com.other.app包下,所以得扩展组件扫描的范围:

package demo.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication(scanBasePackages = {"demo.demo", "com.other.app"})
@ImportResource("classpath:beans/beans.xml")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

额外提醒

  • 如果原WAR项目有自己的web.xml配置,Spring Boot默认不会自动解析,你可以用@ServletComponentScan注解来扫描Servlet、Filter等组件,或者手动在配置类里注册这些组件
  • 要验证原WAR里的静态资源、视图解析器配置是否和Spring Boot的自动配置兼容,如果有冲突,可以通过application.properties或者自定义配置类来调整

做完这些调整后,你的Spring Boot应用应该就能正常启动,并且成功加载原WebMVC项目的所有Bean了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:18:32