Spring 源码分析(一)ApplicationContext
web容器初始化时,因为配置了spring的ContextLoaderListener,所以会执行ContextLoaderListener的contextInitialized(ServletContextEvent event) 方法。
在这个方法中,
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
在initWebApplicationContext中,又调用
this.context = createWebApplicationContext(servletContext, parent);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
这样,在容器初始化时,就在servletcontext中设定了key为 WebApplicationContext.class.getName() + ".ROOT"
value为ApplicationContext
的初始上下文。
所以,通过WebApplicationContextUtils的
public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
即可取得上下文。