Introduction to the SpringBootServletInitializer

Spread the love

1. Overview

In this tutorial, we’ll go through a quick introduction to 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 ServletFilter and ServletContextInitializer beans from the application context to the server.

pom.xml
src
├───main
│   ├───java
│   │   └───com.dailycodebuffer.example.SpringBootServlet
│   │       └───SpringBootServletApplication.java
│   │          
│   │          
│   │          
│   └───resources
└───test
    └───java

2. SpringBootServletInitializer

The first step in producing a deployable war file is to provide a  SpringBootServletInitializer subclass and override its configure method. Doing so makes use of Spring Framework’s Servlet 3.0 support and lets you configure your application when it is launched by the servlet container. Typically, you should update your application’s main class to extend SpringBootServletInitializer, as shown in the following example:

@SpringBootApplication
public class SpringBootServletApplication extends SpringBootServletInitializer {

	public static void main(String[] args) {

		SpringApplication.run(SpringBootServletApplication.class, args);
	}

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

	@RestController
	public static class SpringBootServletController {

		@GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
		public String handler() {
			return "Hello there";
		}
	}

}

The next step is to update your build configuration such that your project produces a war file rather than a jar file. If you use Maven and spring-boot-starter-parent (which configures Maven’s war plugin for you), all you need to do is to modify pom.xml to change the packaging to war, as follows:

<packaging>war</packaging>

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.

Github Source Code

Please find the source code here

Leave a Reply