解决spring boot启动出现Unable to start ServletWebServerApplicationContext due to missing ServletWebServer*

作者 : admin 本文共1414个字,预计阅读时间需要4分钟 发布时间: 2024-06-8 共5人阅读

报错原因    

      今天拉下了一个新的spring boot工程,启动时出现了Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.这个异常。在网上搜索这个错误,有几种说法。

  说法一:是因为缺少一个spring-boot-starter-web依赖。检查pom文件,发现这个依赖已经被引入了,所以不是这个问题。

  说法二:是没有添加@EnableAutoConfiguration这个注解。但是在启动类中已经有@SpringBootApplication这个注解了,这个注解已经包含了@EnableAutoConfiguration注解,所以也不是这个原因,那么到底是什么原因呢。

解决spring boot启动出现Unable to start ServletWebServerApplicationContext due to missing ServletWebServer*插图

发现问题

        可见是在调用getWebServerFactory()方法时候发生错误,没有找到ServletWebServerFactory这个bean,说明在sping容器启动时没有将其注册进去,缺少相关依赖。没有对应的servelt容器,工程当然也就启动不起来。这里多讲一下,springboot工程会通过@EnableAutoConfiguration这个注解去拉去默认配置,该注解通过@Import注解导入了AutoConfigurationImportSelector类。其实这个类,就是导入通过加载配置文件,加载了很多工厂方法的配置类。最终会加载 META-INF/spring.factories这些文件,通过这些文件完成自动装配。@Import注解加载了tomcat,jetty,undertow三个web服务器的配置类。由于没有导入jetty和undertow的相关jar包,这两个类实例的不会真正的加载。到这里分析,为什么会缺少相应的servlet容器?springboot不默认加载了tomcat容器吗,因为tomcat的相关jar包已经在spring-boot-starter-web中引入了,按照之前我们的分析,实际上被加载的容器应该是tomcat,为什么还会找不到呢?

  那么此时我们要分析一下整个工程的依赖情况,看tomcat相关jar包是否被真实的引入。使用mvn dependency:tree命令,对工程进行依赖分析,定位到居然无tomcat相关依赖。

 此时可以发现pom.xml文件中,居然把tomcat排除了,那我排除的去掉即可:

        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    org.springframework.boot
                    spring-boot-starter-tomcat
                
            
        

解决方法

去掉排除设置:

        
            org.springframework.boot
            spring-boot-starter-web
<!--            -->
<!--                -->
<!--                    org.springframework.boot-->
<!--                    spring-boot-starter-tomcat-->
<!--                -->
<!--            -->
        

将pom中的或者整个注释掉,重新编译测试和运行。重新启动工程,启动成功。

解决spring boot启动出现Unable to start ServletWebServerApplicationContext due to missing ServletWebServer*插图(1)

本站无任何商业行为
个人在线分享 » 解决spring boot启动出现Unable to start ServletWebServerApplicationContext due to missing ServletWebServer*
E-->