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

报错原因    

      今天拉下了一个新的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注解,所以也不是这个原因,那么到底是什么原因呢。

发现问题

        可见是在调用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排除了,那我排除的去掉即可:

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

解决方法

去掉排除设置:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
<!--            <exclusions>-->
<!--                <exclusion>-->
<!--                    <groupId>org.springframework.boot</groupId>-->
<!--                    <artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--                </exclusion>-->
<!--            </exclusions>-->
        </dependency>

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

  • 12
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

angelasp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值