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:
- Extends SpringBootServletInitializer
- Marked the embedded servlet container as provided.
- Update packaging to war
Tested with
- Spring Boot 2.1.2.RELEASE
- Tomcat 8 and 9
- Maven 3
In Spring Boot, the new final executable JAR file with embedded server solution may not suitable in all production environments, especially the deployment team (a team with good knowledge of server optimization and monitoring skills, but lack of, the development experience), they want full control of the server, and they don’t touch code, so, we need a traditional WAR file.
1. Extends SpringBootServletInitializer
Update the @SpringBootApplication class to extend SpringBootServletInitializer, and override the configure method.
1.1 Classic Spring Boot JAR deployment.
import org.springframework.boot.autoconfigure.SpringBootApplication; @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); }*/
For multiple main classes, make sure tell Spring Boot which main class to start :
<properties> <!-- The main class to start by executing java -jar --> <start-class>com.mkyong.SpringBootWebApplication</start-class> </properties>
Read this – Spring Boot – Which main class to start
2. Marked the embedded servlet container as provided
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- marked the embedded servlet container as provided --> <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>
Done, build the project and copy the WAR file for deployment.