笔者报错时的运行环境:
Spring Cloud Alibaba:2022.0.0.0-RC2
Spring Cloud:2022.0.0
Spring Boot:3.0.2
Nacos 2.2.3
Maven 3.8.3
JDK 17.0.7
IntelliJ IDEA 2022.3.1 (Ultimate Edition)
问题描述
最近笔者使用 Spring Cloud Gateway 的时候,发生了一个奇怪的事情:Spring Cloud 其它的微服务的运行是正常的,但 Spring Cloud Gateway 一启动就报错。
Spring Cloud Gateway 具体报错内容如下。
202X-XX-XX XX:XX:XX.XXX [WARN] [main] org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:592)
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration$SpringMvcFoundOnClasspathConfiguration': Failed to instantiate [org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration$SpringMvcFoundOnClasspathConfiguration]: Constructor threw exception
202X-XX-XX XX:XX:XX.XXX [INFO] [main] org.apache.juli.logging.DirectJDKLog.log(DirectJDKLog.java:173)
Stopping service [Tomcat]
202X-XX-XX XX:XX:XX.XXX [ERROR] [main] org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter.report(LoggingFailureAnalysisReporter.java:40)
***************************
APPLICATION FAILED TO START
***************************
Description:
Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway.
Action:
Please set spring.main.web-application-type=reactive or remove spring-boot-starter-web dependency.
问题原因&解决办法
原来,这是因为 Spring Cloud Gateway 的项目中不能使用 Spring MVC 的依赖,而笔者不小心通过依赖其它模块而间接引用了该 Spring MVC 的依赖。
也就是说,在 Spring Cloud Gateway 的项目中不能使用如下依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如果不小心引用了,则需要排除 Spring MVC 依赖。
<dependency>
<groupId>某个引用了 Spring MVC 依赖的模块的组 ID</groupId>
<artifactId>该模块的工件 ID</artifactId>
<version>该工件的版本号</version>
<exclusions>
<!-- Spring Cloud Gateway 项目中不能使用 spring-boot-starter-web 依赖-->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
如果想确定自己的 Maven 模块有没有依赖 Spring MVC,可以在 IntelliJ IDEA 中查看。
比方说,下面这种情况就属于依赖了 Spring MVC,Spring Cloud Gateway 引用这个依赖就会在启动时报错。