Deploying and Running a SpringBoot Project in Tomcat

A record of the process for packaging a SpringBoot project and deploying it to run in a Tomcat container (you can never guess what other bizarre requirements a customer might have).

Contents

Package Spring Boot as a WAR

Package the Spring Boot application as a WAR and run it in a Tomcat container

1. Modify the packaging type in the Maven file

<packaging>war</packaging>

2. Remove Spring Boot’s Embedded Tomcat

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

Review the lifecycle of Maven dependencies

  1. compile: Compile dependency scope, the default dependency scope. The dependency is effective in all three classpath: compile, test, and runtime.
  2. test: Test dependency scope, effective only in the test classpath.
  3. provided: Provided dependency scope, effective for compile and test classpath, but ineffective for runtime classpath. For example, servlet-api is needed as a dependency during compilation and testing, but when running the project, the container already provides it, so there is no need to Maven include it again.
  4. runtime: Runtime dependency scope. Effective for test and runtime classpath, but ineffective at compile time. For example, a jdbc driver package: compiling the project's main code only requires the JDBC interface provided by JDK; the concrete JDBC driver that implements the interface is needed only when running tests or the project.
  5. system: System dependency scope, consistent with the provided dependency scope. However, when using a system dependency, the path to the dependency file must be explicitly specified through the systemPath element. Since this type of dependency is not resolved through a Maven repository and is often tied to the local system, it may make the build non-portable and should therefore be used with caution. The systemPath element can reference environment variables.
  6. import: Used for one dependencyManagement to inherit from another dependencyManagement.

3. Modify the startup class

@SpringBootApplication
// 继承 SpringBootServletInitializer 类
public class MapApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(MapApplication.class, args);
    }

    //重写configure方法
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MapApplication.class);
    }
}

4. Repackaging

mvn clean
mvn package

5. Deploy the WAR package

Move the WAR file from the target directory into Tomcat’s webapps folder.

Of course, you can also use Baota—or whatever you prefer.

6. Start Tomcat

Check the Tomcat logs to confirm it started successfully.

image-20240805194218426

7. Celebrate with a Coke?

[dog]