ServletContainerInitializer(in org.springframework.web) is the interface which allows a library/runtime to be notified of a web application’s startup phase and perform any required programmatic registration of servlets, filters, and listeners in response to it.
The spring also has an implementation for it. That is ServletContainerInitializer, When you started a spring apllication, it will be loaded and instantiated and have its onStartup method invoked by any Servlet-compliant container during container startup assuming the the spring-web moodule JAR is present on the classpath.
Assuming that one or more WebApplicationInitializer types are detected, they will be instantiated Then the WebApplicationInitializer.onStartup(ServletContext) method will be invoked on each instance, delegating the ServletContext such that each instance may register and configure servlets(Spring’s DispatcherServlet(), listeners(Spring’s ContextLoaderListener), or any other Servlet API features(filters).
Below is the code for SpringServletContainerInitializer.
A brief description of the action it performs is as follows :
Repeat the Set <Class<?> received as a parameter to create a Web Application Initializer and put it in the initializers.
Sort the initializers and run the WebApplicationInitializer#onStartup method.
If then, what is WebApplicationInitializer?
WebApplicationInitializer
WebApplicationInitializer is the Interface to be implemented in Servlet environments in order to configure the ServletContext programmatically.
As you can see from above, Implementations of this SPI will be detected automatically by SpringServletContainerInitializer, which itself is bootstrapped automatically by any Servlet container.
By implementing this WebApplicationInitializer, you can set the WebApplication in detail based on code. (like above)
There are several implementations of the WebApplicationInitializer that are provided by default. AbstractAnnotationConfigDispatcherServletInitializer is the base class to initialize Spring application in Servlet container environment, so we will check that class and its parent class.
If look at the order of operation from the bottom,
AbstractAnnotationConfigDispatcherServletInitializer registers the ContextLoaderListener, including the settings of the class with the specific Annotation(@Configuration), and creates the ServletApplicationContext,
AbstractContextLoaderInitializer registers the ContextLoaderListener,
AbstractDispatcherServletInitializer creates DispatcherServlet by register ServletFilters on servletContext,
The order of execution is the order of calls, not the parent-child order. To explain it in detail by looking at the code,
AbstractAnnotationConfigDispatcherServletInitializer registers the ContextLoaderListener, including the settings of the class with the specific Annotation(@Configuration), and creates the ServletApplicationContext,
AbstractContextLoaderInitializer registers the ContextLoaderListener,