tomcat找到我们应用中的默认sping-web包下/meta- INF/service/javax.servlet.ServletContainerInitializer
在调用SpringServletContainerInitializer.onStartUp() 之前会找到所有实现了WebApplicationInitializer的类,传入到OnStartup的 webAppInitializerClasses参数中,并传入Servlet上下文对象
org.springframework.web.SpringServletContainerInitializer#onStartup
@Override public void onStartup(@Nullable Set2. 创建父容器 ContextLoaderListener> webAppInitializerClasses, ServletContext servletContext) throws ServletException { List initializers = Collections.emptyList(); if (webAppInitializerClasses != null) { initializers = new ArrayList<>(webAppInitializerClasses.size()); for (Class> waiClass : webAppInitializerClasses) { // 接口和抽象类servlet容器也会给我们,但是我们不要 // 排除接口和容器 if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) { try { // 实例化,然后添加到集合中 initializers.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(waiClass).newInstance()); } catch (Throwable ex) { throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex); } } } } if (initializers.isEmpty()) { servletContext.log("No Spring WebApplicationInitializer types detected on classpath"); return; } servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath"); AnnotationAwareOrderComparator.sort(initializers); // 调用initializer.onStartup 进行扩展 for (WebApplicationInitializer initializer : initializers) { initializer.onStartup(servletContext); } }
org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#onStartup
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//registerContextLoaderListener ok
super.onStartup(servletContext);
// registerDispatcherServlet
registerDispatcherServlet(servletContext);
}
protected void registerContextLoaderListener(ServletContext servletContext) {
// 创建父容器 ,
WebApplicationContext rootAppContext = createRootApplicationContext();
if (rootAppContext != null) {
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
// 设置初始化器
listener.setContextInitializers(getRootApplicationContextInitializers());
servletContext.addListener(listener);
}
else {
logger.debug("No ContextLoaderListener registered, as " +
"createRootApplicationContext() did not return an application context");
}
}
3. 创建子容器DispatcherServlet
org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#registerDispatcherServlet
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty");
// 创建子容器
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext, "createServletApplicationContext() must not return null");
// 创建DispatcherServlet
frameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
Assert.notNull(dispatcherServlet, "createDispatcherServlet(WebApplicationContext) must not return null");
// 初始化器
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
if (registration == null) {
throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
"Check if there is another servlet registered under the same name.");
}
// 启动时加载
registration.setLoadonStartup(1);
// 映射
registration.addMapping(getServletMappings());
// 是否异步支持
registration.setAsyncSupported(isAsyncSupported());
// 设置DispatcherServlet的过滤器
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
// 空方法, 可以再对DispatcherServlet进行定制
customizeRegistration(registration);
}
4.初始化ContextLoaderListener
外置tomcat会帮我们调用ContextLoaderListener#contextInitialized 进行初始化;
前面只是创建Spring容器,此处调用configureAndRefreshWebApplicationContext()方法从而调用refresh()方法
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// 设置id
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
// 设置ServletContext到spring上下文
wac.setServletContext(sc);
// 获得servlet容器中的全局参数contextConfigLocation (xml)
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
// 在容器加载前 可以通过设置初始化参数contextInitializerClasses、globalInitializerClasses 进行扩展
customizeContext(sc, wac);
// 刷新容器
wac.refresh();
}
5. 初始化DispatcherServlet
外置tomcat会帮我们调用DispatcherServlet#init()
最终调用org.springframework.web.servlet.frameworkServlet#initWebApplicationContext
protected WebApplicationContext initWebApplicationContext() {
// 获得ContextLoaderListener存的父容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// 获得子容器
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// 如果没有设置父容器 spring doGetBean
if (cwac.getParent() == null) {
cwac.setParent(rootContext);
}
// 配置并且加载子容器
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// 从servlet上下文根据名字从域里面获取
wac = findWebApplicationContext();
}
if (wac == null) {
// xml会在这里创建
wac = createWebApplicationContext(rootContext);
}
//refreshEventReceived 它会在容器加载完设置为true (通过事件onApplicationEvent)
// springboot在这初始化组件
if (!this.refreshEventReceived) {
synchronized (this.onRefreshMonitor) {
onRefresh(wac);
}
}
if (this.publishContext) {
// 将当前容器放到servlet域中, 可以再创建子容器
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
}
return wac;
}
并且监听子容器的ContextRefreshListener 去初始化SpringMvc的组件
org.springframework.web.servlet.DispatcherServlet#initStrategies
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
tomcat 的流程,后续补充...
欢迎跟帖:caicongyang_CSDN博客-Java基础,sshm,Hadoop/spark领域博主



