A Spring WebApplicationInitializer uses a Servlet 3.0+ implementation to configure ServletContext programmatically.
Here's the sample code of the WebApplicationInitializer class, called MyApplicationInitializer.kt:
class MyApplicationInitializer: WebApplicationInitializer {
@Throws(ServletException::class)
override fun onStartup(container: ServletContext) {
val ctx = AnnotationConfigWebApplicationContext()
ctx.servletContext = container
val servlet = container.addServlet("dispatcher", DispatcherServlet(ctx))
servlet.setLoadOnStartup(1)
servlet.addMapping("/")
}
}
This class will help to map the project URL path, "", using start. As we are using a code-based annotation in place of an XML configuration, we are using AnnotationConfigWebApplicationContext.
Then we have created and registered the dispatcher servlet.