You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot启动报错:缺少ServletWebServerFactory bean解决方案求助

解决Spring Boot启动报错:Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

我之前也碰到过一模一样的问题,就是用Spring Initializr生成的空项目,啥业务逻辑都没加,在Eclipse Oxygen里启动就报这个错,折腾了好一阵才解决,给你几个亲测有效的思路:

1. 检查启动类的注解与包路径

Spring Boot Web项目的启动类必须标注@SpringBootApplication,而且得放在项目根包路径下(也就是所有业务类的父包层级)。比如你的项目包是com.example.demo,启动类DemoApplication就得直接放在这个包下面,不能丢到子包里去。如果注解错了或者位置不对,Spring没法自动触发Web服务器的自动配置。

正确的启动类示例:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

2. 确认Web依赖是否正确引入

既然是Web项目,必须包含spring-boot-starter-web依赖,不然Spring不会自动引入Tomcat(或其他Web服务器)的相关配置组件。

Maven项目(pom.xml)

确保有这段依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradle项目(build.gradle)

确保有这段依赖:

implementation 'org.springframework.boot:spring-boot-starter-web'

如果已经加了依赖,试试右键项目 → Maven → Update Project(Eclipse环境),或者执行mvn clean install命令刷新依赖,有时候依赖没拉全也会触发这个报错。

3. 排查是否误设非Web启动配置

如果你的项目里不小心加了spring-boot-starter(仅基础依赖,不含Web模块),或者在application.properties/application.yml里配置了spring.main.web-application-type=none,会让Spring Boot以非Web应用模式启动,自然不会创建ServletWebServerFactory bean。

打开配置文件检查,要是有类似配置,删掉或者改成:

spring.main.web-application-type=servlet

4. 清除Eclipse Oxygen的缓存问题

Eclipse Oxygen有时候会有缓存紊乱的情况,试试这几步:

  • 右键项目 → Run As → Maven Clean,完成后再Run As → Maven Install
  • 右键项目 → Spring → Boot Dashboard,在Dashboard里重启应用
  • 极端情况可以备份项目后,删掉项目目录下的.metadata文件夹,重新导入项目

我当时就是因为Eclipse缓存了旧的依赖配置,清掉之后就正常启动了。


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

火山引擎 最新活动