By default, Spring Boot applications are built as stand-alone executable JARs with an embedded Tomcat. With some additional configuration, a Spring Boot application can be built as a WAR file to deploy to an existing Tomcat, or other servlet container, instance.
These steps can be used to set up a project that can switch easily between building a stand-alone JAR or a WAR for deployment by specifying a Maven profile when building the deployment package. Notes are provided for cases that use other available servlet containers (Jetty and Undertow).
Make the following changes to the pom.xml
file:
<project>
...
<packaging>${package.type}</packaging>
...
<profiles>
<profile>
<id>standalone</id>
<!--
Standalone will be the default. Move the "activation" section to the other profile to make it the default.
-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<package.type>jar</package.type>
<start-class>com.example.YourApplicationStandalone</start-class>
</properties>
</profile>
<profile>
<id>tomcat</id>
<properties>
<package.type>war</package.type>
<start-class>com.example.YourApplication</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<!--
Replace with "spring-boot-starter-jetty" or "spring-boot-starter-undertow" if using either of those.
-->
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
You will need two versions of your start class:
@Profile("standalone")
@SpringBootApplication
public class YourApplicationStandalone {
public static void main(String[] args) {
SpringApplication.run(YourApplicationStandalone.class, args);
}
}
@Profile("tomcat")
@SpringBootApplication
public class YourApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
To build the default (standalone) package:
mvn package
To build a WAR file:
mvn package -Ptomcat