Spring Boot 启动报错:MissingServletWebServerFactoryBean 的排查与解决
问题现象
启动 Spring Boot 应用时控制台输出以下错误:
APPLICATION FAILED TO START
Description:
Web application could not be started as there was no
org.springframework.boot.web.servlet.server.ServletWebServerFactory bean defined in the context.
Action:
Check your application's dependencies for a supported servlet web server.
Check the configured web application type.
错误信息指向 ServletWebServerFactory Bean 缺失,但实际上项目中已经引入了 spring-boot-starter-web 依赖,内嵌 Tomcat 的 jar 包也在 classpath 中。
排查过程
检查 pom.xml,确认存在 Web 依赖:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
检查启动类,发现问题所在:启动类上缺少 @SpringBootApplication 注解。
java
// 错误写法
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
原因分析
SpringApplication.run() 虽然能启动 Spring 容器,但不会自动启用 Spring Boot 的自动配置机制。ServletWebServerFactory Bean 由 ServletWebServerFactoryAutoConfiguration 自动配置类创建,而该类只有在 @EnableAutoConfiguration 生效时才会被加载。
@SpringBootApplication 是一个组合注解,包含了三个核心注解:
@SpringBootConfiguration:标注这是一个配置类,等同于@Configuration@EnableAutoConfiguration:开启自动配置,是 Spring Boot 最核心的注解@ComponentScan:启用组件扫描,默认扫描当前包及其子包
缺少 @SpringBootApplication,实际上缺少的是 @EnableAutoConfiguration。没有自动配置,Spring Boot 就不会创建 TomcatServletWebServerFactory 实例,自然也就无法启动内嵌 Web 容器。
修复方案
在启动类上添加 @SpringBootApplication 注解:
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
重新启动,控制台输出正常启动日志:
2026-08-30 11:30:24.034 INFO 73324 --- [main] com.xie.springboot.MyApplication: Starting MyApplication
2026-08-30 11:30:25.234 INFO 73324 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat started on port 8080
为什么 @SpringBootApplication 是 Spring Boot 的入口?
@EnableAutoConfiguration 背后依赖 ImportSelector 机制。它通过 AutoConfigurationImportSelector 从 META-INF/spring.factories 文件中读取 EnableAutoConfiguration 键对应的配置类列表。ServletWebServerFactoryAutoConfiguration 就在这个列表中,它检测到 classpath 有 Servlet 类和 Tomcat 相关类后,就会创建 TomcatServletWebServerFactory Bean。没有 @EnableAutoConfiguration,这条加载链路就断了。
延伸:@SpringBootApplication 的 exclude 属性
如果启动类上写了 @SpringBootApplication(exclude = {ServletWebServerFactoryAutoConfiguration.class}),也会出现同样的错误。排查时可以检查是否误排除了 Web 容器相关的自动配置类。
总结
MissingServletWebServerFactoryBean 这个错误虽然指向 ServletWebServerFactory Bean 缺失,但根本原因通常不是依赖问题,而是自动配置没有生效。最直接的原因是启动类缺少 @SpringBootApplication 注解。Spring Boot 的自动配置机制依赖于 @EnableAutoConfiguration,而 @SpringBootApplication 是启用它的标准方式。如果确认已经添加该注解但仍然报错,再检查是否通过 exclude 属性排除了相关配置类,或 application.yml 中是否将 web-application-type 设置为了 none。