Root Application Context
As such, it typically contains middle-tier services, data sources, etc.

Servlet Application Context
As such, it typically contains controllers, view resolvers, locale resolvers, and other web-related beans.

Root Application Context 用来初始化 ContextLoaderListener 对象,并将该对象注册到 Servlet 容器中

Servlet Application Context 用来初始化 DispatcherServlet 对象,并将该对象注册到 Servlet 容器中,随后添加 Filters, 添加 Mapping 映射, 当然用户还可以通过 customizeRegistration(ServletRegistration.Dynamic registration) 来进行自定义之后的操作,如配置 Multipart 处理的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Delegate the ServletContext to any WebApplicationInitializer implementations present on the application classpath.
Because this class declares @HandlesTypes(WebApplicationInitializer.class), Servlet 3.0+ containers will automatically scan the classpath for implementations of Spring's WebApplicationInitializer interface and provide the set of all such types to the webAppInitializerClasses parameter of this method.

Assuming that one or more WebApplicationInitializer types are detected, they will be instantiated (and sorted if the @@Order annotation is present or the Ordered interface has been implemented). Then the WebApplicationInitializer.onStartup(ServletContext) method will be invoked on each instance, delegating the ServletContext such that each instance may register and configure servlets such as Spring's DispatcherServlet, listeners such as Spring's ContextLoaderListener, or any other Servlet API componentry such as filters.

/* Servlet 3.0+ 会自动在应用的 classpath 中寻找 WebApplicationInitializer 的实现类,并对每一个实现类进行实例化,将 ServletContext 委托给他们,对每一个实例调用 WebApplicationInitializer.onStartup(ServletContext), 加载和注册所有的 ServletListenerFilter */

If no WebApplicationInitializer implementations are found on the classpath, this method is effectively a no-op. An INFO-level log message will be issued notifying the user that the ServletContainerInitializer has indeed been invoked but that no WebApplicationInitializer implementations were found.


// org.springframework.web.SpringServletContainerInitializer

@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, @NotNull ServletContext servletContext) throws ServletException {

}
}
1
2
3
4
5
ServletContainerInitializer

SpringServletContainerInitializer

WebApplicationInitializer