Create WAR file in Spring Boot

In this post, we’ll show you how to create war file in spring boot. This uses our simple spring boot application from Creating Simple Spring Boot Web Application Tutorial.

Create WAR File in Spring Boot

This is just a three step simple procedure to package your application into war.

  1. Extending Main Class

    First, we extend our main class to SpringBootServletInitializer. This tells spring that your main class will be the entry point to initialize your project in server.

    @SpringBootApplication
    public class Application extends SpringBootServletInitializer{
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
  2. Overriding configure method

    Next, we overload the configure method of SpringBootServletInitializer. We tell spring to build the sources from our Main class. Your final Main class should look like this:

    @SpringBootApplication
    public class Application extends SpringBootServletInitializer{
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(Application.class);
        }
    }
    
  3. Configure Packaging to WAR

    Finally, we tell maven to package the project in to WAR. In your pom.xml, change the attribute value for packaging from jar to war

        war
    

    Then try to build your project using:

    mvn package
    

    For Gradle Project, please see this Packaging executable jar and war files in Gradle link to configure .gradle file to build war file.

With this, you can now package your application with jar or war file. Just change the packaging to either jar or war. And also you can still run your main method in your IDE to develop the application.

Share this tutorial!