Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeromy-vandusen-obs/dd3155ead8a2806df279dd0f1ad454d5 to your computer and use it in GitHub Desktop.
Save jeromy-vandusen-obs/dd3155ead8a2806df279dd0f1ad454d5 to your computer and use it in GitHub Desktop.
Using Maven Profiles to Select Spring Boot Deployment Type

Using Maven Profiles to Select Spring Boot Deployment Type

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).

The POM

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>

The Code

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);
  }
}

Packaging

To build the default (standalone) package:

mvn package

To build a WAR file:

mvn package -Ptomcat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment