test environment
Spring Boot 2.7.5
Tomcat 9.0.69
The default packaging method in the spring boot project is the jar package. If you want to package the war package, you need to change the configuration (take Maven as an example)
pom.xml
<packaging>war</packaging>
After the change, it is indeed a war package after packaging, but this war package cannot be run in the external Tomcat. Check the official documentation, there is such a warning when the war package is created.
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.
How to solve?
In fact, the method is very simple. Create a new ServletInitializer file in the same directory as the Application startup file, with the following content
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);
}
}
Remember to change the package name and startup class name.
Add tomcat dependency in pom.xml, and set scope to provided, so that the Tomcat that comes with the spring boot project will not affect the external Tomcat
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>