DispatcherServlet extends FrameworkServlet extends HttpServletBean extends HttpServlet
初始化:HttpServletBean.init() -> FrameworkServlet.initServletBean -> FrameworkServlet.initWebApplicationContext()
initWebApplicationContext:
1. 调用WebApplicationContextUtils.getWebApplicationContext(ServletContext)获取当前web容器中的根WebApplicationContext rootContext,该rootContext通常由ContextLoaderListener生成(因为该方法实际是获取web容器中attrName为org.springframework.web.context.WebApplicationContext.ROOT的WebApplicationContext,而该attrName由ContextLoaderListener设置到web容器中)
2. 判断本Servlet所属的WebApplicationContext wac是否在init之前就由别的步骤注入了?即判断wac是否为null
2.1. 若非空(wac已存在),则将rootContext设为wac的parent,再调用configureAndRefreshWebApplicationContext(wac)
2.2. 若为空(wac不存在),则先调用findWebApplicationContext寻找web容器中是否已经存在同名(attrName,定义见5)的WebApplicationContext(首次启动web容器时通常不存在;当servlet初始化失败,web容器自动重启时可能存在),若还是不存在则调用createWebApplicationContext生成一个新的WebApplicationContext
2.2.1. createWebApplicationContext(rootContext): 首先创建一个全新的WebApplicationContext wac,再将rootContext设为wac的parent,再调用configureAndRefreshWebApplicationContext(wac)
3. configureAndRefreshWebApplicationContext(wac): 先设置wac的各项配置和环境参数,后调用wac.refresh()
4. DispatcherServlet.onRefresh(wac): 初始化与web mvc相关的spring组件
5. 调用ServletContext.setAttribute将wac注册到web容器中,attrName为org.springframework.web.servlet.FrameworkServlet.CONTEXT.${servlet-name}