测试环境
Spring Boot 2.7.5
Tomcat 9.0.69
spring boot项目中默认的打包方式是jar包,如果想要打war包,就需要更改配置(以Maven为例)
pom.xml
<packaging>war</packaging>
更改过后,打包后确实是war包,但是这个war包放在外部的Tomcat中无法运行。查看官方文档,打war包的时候有这样的警告。
Because Spring WebFlux does not strictly depend on the servlet API and applications are deployed by default on an embedded Reactor Netty server, War deployment is not supported for WebFlux applications.
如何解决?
其实方法还是很简单的,在Application启动文件同级目录下新建一个ServletInitializer文件,内容如下
package com.demo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
}
记得更改包名和启动类名称。
pom.xml中新增tomcat依赖,并设置scope为provided,这样spring boot项目中自带的Tomcat就不会影响外部的Tomcat
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>