总览
Tomcat容器启动阶段
│
├─ 1. StandardContext#startInternal()
│ │
│ ├─ 1.1 调用SpringServletContainerInitializer#onStartup()
│ │ │
│ │ ├─ 注册ContextLoaderListener(父上下文创建)
│ │ └─ 注册DispatcherServlet(子上下文创建)
│ │
│ ├─ 1.2 StandardContext#listenerStart()
│ │ │
│ │ └─ ContextLoaderListener#contextInitialized()
│ │ └─ 父上下文刷新(wac.refresh())
│ │
│ └─ 1.3 StandardContext#loadOnStartup()
│ │
│ └─ DispatcherServlet#init()
│ └─ 子上下文刷新(wac.refresh())
│
└─ 完成父子上下文初始化
父子上下文加载时机
org.apache.catalina.util.LifecycleBase#start()
org.apache.catalina.core.StandardContext#startInternal()
1. ServletContainerInitializer触发(Servlet 3.0+规范)
org.springframework.web.SpringServletContainerInitializer#onStartup()
1.1 创建父上下文
org.springframework.web.context.AbstractContextLoaderInitializer#onStartup()
org.springframework.web.context.AbstractContextLoaderInitializer#registerContextLoaderListener()
WebApplicationContext rootAppContext = createRootApplicationContext()
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext) | new ContextLoader(rootAppContext)
servletContext.addListener(listener)
1.2 创建子上下文
org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#registerDispatcherServlet()
WebApplicationContext servletAppContext = createServletApplicationContext()
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext) | new DispatcherServlet(servletAppContext) | new FrameworkServlet(servletAppContext)
servletContext.addServlet(servletName, dispatcherServlet)
2. Listener初始化阶段
org.apache.catalina.core.StandardContext#listenerStart()
org.springframework.web.context.ContextLoaderListener.contextInitialized
org.springframework.web.context.ContextLoader.initWebApplicationContext
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext
wac.refresh() # 刷新父上下文
3. Servlet初始化阶段
org.apache.catalina.core.StandardContext#loadOnStartup()
org.apache.catalina.core.StandardWrapper.load
org.apache.catalina.core.StandardWrapper.loadServlet
org.apache.catalina.core.StandardWrapper.initServlet
javax.servlet.GenericServlet.init()
org.springframework.web.servlet.HttpServletBean.init
org.springframework.web.servlet.FrameworkServlet#initServletBean()
org.springframework.web.servlet.FrameworkServlet#configureAndRefreshWebApplicationContext()
wac.refresh() # 刷新子上下文