How to deploy Spring boot app as .war file

Hello from ToraCode.

If you find your cloud platform doesn’t support container service or deploying standalone application you may find it annoying deploying your app in the cloud. But you can still try creating a traditional .war file to deploy into a container like Tomcat 8, Wildfly 10 or other container.

It’s very easy to deploy Spring boot app as .war . You have to just follow those few steps.

Extend your application class with SpringBootServletInitializer and override configure() method like this:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

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

Next, update your configuration so that your project can produce .war file rather than .jar file.

If you’re using Maven then modify pom.xml file to change the packaging type to .war.

<packaging>war</packaging>

If you’re using Gradle then modify build.gradle

apply plugin: 'war'

Finally if you find your project has spring-boot-starter-tomcat dependency, then change it to provided so that it’s not included when packaging your application.

For maven:

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

If you use Gradle rather than Maven, change your dependency like this,

providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'

Now,

  • Right click on your project, choose Maven->Update Project.. (It will update your project for the latest configuration)
  • Again Right click your project->properties->project facets->Uncheck Cloud Foundry Standalone Application (So that your project can be added to Tomcat container to run)

Well that’s what you needed to do.

You can now run your project into tomcat or other containers or deploy .war file from it.

 

Leave a Reply

Your email address will not be published. Required fields are marked *