ContextLoaderListener extends ContextLoader implements ServletContextListener
WebApplicationContext初始化的代码逻辑在ContextLoader中,供实现ServletContextListener接口的contextInitialized和contextDestroyed方法调用
初始化:ContextLoaderListener.contextInitialized -> ContextLoader.initWebApplicationContext(ServletContext)
initWebApplicationContext:
1. 检查web容器中是否存在同名(attrName,定义见5)的WebApplicationContext,若存在则报错(通常若在web.xml中定义了多个ContextLoaderListener,则必然存在)
2. 调用createWebApplicationContext创建新的WebApplicationContext context
3. 若context的parent为null,调用loadParentContext从web容器中检查是否存在外部的父ApplicationContext(通常不存在),并获取,设置为context的parent
4. 调用ContextLoader.configureAndRefreshWebApplicationContext
4.1. 设置context的各项配置和环境参数
4.2. 调用customizeContext,用于处理一些自定义的代码
4.3. context.refresh()
5. 调用ServletContext.setAttribute将context注册到web容器中,attrName为org.springframework.web.context.WebApplicationContext.ROOT
6. 处理ClassLoader与context的映射关系