在启动SpringBoot程序时报如下异常:

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:162) ~[spring-boot-2.4.1.jar:2.4.1]

导致上述异常的原因往往是“粗心大意”,对的,就是哪里漏引入依赖或哪里用错了类。

依赖引入缺失

SpringBoot项目中,如果未引入web对应的starter,则会抛出上述异常。因此检查项目中是否有直接引入,或间接引入如下依赖:

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

如果没有,添加上去再试试。

main方法启动参数错误

正常来说SpringBoot项目会自动生成启动类和main方法,但如果你手动去写往往会写错,一不留意提示信息,就将参数类写错了,导致上述异常:

@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {

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

比如上述代码中本应该在run方法中传入EurekaApplication.class,但因为操作的太快,导致传入了同样前缀的另外一个类,启动异常就很正常了。该为正确的参数。排查一下是否犯了类似的错误。

依赖冲突导致

由于SpringBoot引入的依赖可能会间接引起其他的依赖,比如内置的Tomcat,这就会导致与其他地方的Tomcat版本冲突。此时检查冲突jar包,排除掉。这里以Tomcat为例。

Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean插图

类似的也有其他类导致冲突,导致出现异常,jar的依赖关系要理清楚。

默认使用的嵌入式Tomcat容器无法启动,还可排查以下几方面进行解决:

(1)删除Maven本地库中有错的tomcat-embed-core,再次构建下载新的tomcat-embed-core,构建错误消失,成功构建完成。

(2)上述截图中,把嵌入的tomcat注释一下就可以了

(3)排除嵌入式tomcat,指定本地的tomcat即可。

idea配置导致

在ibase4j的主maven配置文件pom.xm里有关springboot的依赖tomcat有如下配置:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
</dependency>

scope:provided表示产于编译运行,但不参与打包,打包由生产环境提供。把scope的provided改成了complie,可以启动成功。

在idea启动配置项中可修改对应的scope来解决此问题,选择Edit Configuration…

Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean插图1

选择SpringBoot的配置,勾上Include dependencies with “Provided” scope,再次启动即可解决问题。

如果你发现同样的代码,在别人或其他地方或其他ide可运行,则可针对运行环境进行排查,比如idea的配置。

或者直接修改scope的范围,比如注释掉scope采用默认的。

打包缓存导致

如果修改之后还有问题,可考虑重新通过maven进行打包,通过maven命令或idea插件都可以。不过在执行打包最好加上clean命令。

Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean插图2

版本问题

springboot  2.0.0 版本需要jdk 1.8以上 ,tomcat版本8.5以上,出现如上错误,可检查tomcat版本是否符合要求。



Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean插图3

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2021/01/14/springboot-idea-servletwebserverfactory/