I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll go through a quick introduction of the SpringBootServletInitializer.

This is an extension of WebApplicationInitializer which runs a SpringApplication from a traditional WAR archive deployed on a web container. This class binds Servlet, Filter and ServletContextInitializer beans from the application context to the server.

Extending the SpringBootServletInitializer class also allows us to configure our application when it’s run by the servlet container, by overriding the configure() method.

2. SpringBootServletInitializer

To get more practical, we’ll show an example of a main class that extends the Initializer class.

Our @SpringBootApplication class called WarInitializerApplication extends the SpringBootServletInitializer and overrides the configure() method. That method uses SpringApplicationBuilder to simply register our class as a configuration class of the application:

@SpringBootApplication
public class WarInitializerApplication extends SpringBootServletInitializer {

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

    public static void main(String[] args) {
        SpringApplication sa = new SpringApplication(
          WarInitializerApplication.class);
        sa.run(args);
    }

    @RestController
    public static class WarInitializerController {

        @GetMapping("/")
        public String handler() {
           // ...
        }
    }
}

Now, if we package our application as a WAR, we’ll be able to deploy it on any web container in a traditional way, which will also execute the logic we added in the configure() method.

If we want to package it as a JAR file, then we’ll need to add the same logic to the main() method so that the embedded container can pick it up as well.

3. Conclusion

In this article, we introduced the SpringBootServletInitializer and demonstrated how we can use it to run Spring Boot applications from a classical WAR archive.

The complete source code for the example is available over on GitHub. This is a Maven-based project, so it can be imported and used as-is.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
Angus
Guest
Angus

Can this method be used for running the webapp as an exploded war file in tomcat?

Loredana Crusoveanu
Editor

Hey Angus,

Sure, this will help you build a war file. You can then use the maven war plugin to build an exploded directory: https://maven.apache.org/plugins/maven-war-plugin/exploded-mojo.html