Spring Boot – Create a Deployable War File

In general Spring Boot applications are deployed as jar files but Spring Boot applications can also deployed as war files. In this blog post I will explain step by step process to convert Spring Boot application which is packaged as jar file to deployable war file.

Spring Boot application when packaged as jar files they contain embedded Tomcat, If we want to deploy them as war file, we need to exclude the embedded Tomcat and some other small changes to package them as war file.

Creating a Deployable War File

1. Update Configuration files

i. Change packaging to war file

The first step is to update your build configuration such that your project produces a war file
rather than a jar file.
If we use maven, we need modify pom.xml.to change the packaging to war.

	<groupId>dev.fullstackcode.eis</groupId>
	<artifactId>springboot-crud-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>  <!-- change packaging to war file -->
        <name>springboot-crud-example</name>Code language: HTML, XML (xml)

If we use Gradle, we need to modify build.gradle to apply the war plugin to the project, as follows:

apply plugin: 'war'Code language: Java (java)

ii. Change embedded tomcat container to provided.

By default, Spring Boot application comes with embedded tomcat server. So we need to mark the tomcat server as provided.

<dependencies>
<!-- ... -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope> <!-- mark tomcat server as provided -->
  </dependency>
<!-- ... -->
</dependencies>Code language: HTML, XML (xml)

If you use Gradle, the following example marks the servlet container (Tomcat, in this case) as being
provided:

dependencies {
// ...
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
// ...
}Code language: Java (java)

Note

provided Runtime is preferred to Gradle’s compileOnly configuration. Among other limitations, compileOnly dependencies are not on the test classpath, so any web-based integration tests fail

2. Provide a SpringBootServletInitializer subclass

The next step in producing a deployable war file is to provide a SpringBootServletInitializer
subclass and override its configure method.

@SpringBootApplication
public class SpringbootCrudExampleApplication extends SpringBootServletInitializer {

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

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
	{
		return application.sources(SpringbootCrudExampleApplication.class);
	}

}Code language: Java (java)

Now If you run following maven command, it should create war file in the target folder.

mvn clean packageCode language: Java (java)

Similar Posts