SpringBootServletInitializer Class

SpringBootServletInitializer class 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.

SpringBootServletInitializer Class Methods

protected SpringApplicationBuilder createSpringApplicationBuilder() - Returns the SpringApplicationBuilder that is used to configure and create the SpringApplication.

void onStartup(ServletContext servletContext)

protected WebApplicationContext run(SpringApplication application) - Called to run a fully configured SpringApplication.

protected void setRegisterErrorPageFilter(boolean registerErrorPageFilter) - Set if the ErrorPageFilter should be registered.

SpringBootServletInitializer Class Usage (Example)

In order to create a deployable war file and deploy on external tomcat, let's consider we have Application or Main class which extends the SpringBootServletInitializer and overrides the configure() method. That method uses SpringApplicationBuilder to simply register our class as a configuration class of the application:

If it is a maven project and to create a war file using the following command:

mvn clean install

Once maven builds success then WAR file is generated under a target folder. Just copy war file to external tomcat webapps folder and start the tomcat server.

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.

Note that a WebApplicationInitializer interface(SpringBootServletInitializer implementation) is only needed if you are building a war file and deploying it. If you prefer to run an embedded web server then you won't need this at all.