Spring Boot – Deploy WAR file to Tomcat

In this article, we will show you how to create a Spring Boot traditional WAR file and deploy to a Tomcat servlet container.

In Spring Boot, to create a WAR for deployment, we need 3 steps:

  1. Extends SpringBootServletInitializer
  2. Marked the embedded servlet container as provided.
  3. Update packaging to war

Tested with

  • Spring Boot 2.1.2.RELEASE
  • Tomcat 8 and 9
  • Maven 3 

1. Extends SpringBootServletInitializer
Update the @SpringBootApplication class to extend SpringBootServletInitializer, and override the configure method.

1.1 Classic Spring Boot JAR deployment.
@SpringBootApplication
public class StartWebApplication {

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

}
1.2 For WAR deployment.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class StartWebApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(StartWebApplication.class);
    }
}


/*@SpringBootApplication
public class StartWebApplication {

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

}*/

2. Marked the embedded servlet container as provided
<dependencies>

 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

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

</dependencies>
3. Update packaging to war
<packaging>war</packaging>
Source : mkyong.com