The ApplicationContext
is where your Spring beans live. The purpose of the ContextLoaderListener
is two-fold:
-
to tie the lifecycle of the
ApplicationContext
to the lifecycle of theServletContext
and -
to automate the creation of the
ApplicationContext
, so you don't have to write explicit code to do create it - it's a convenience function.
Another convenient thing about the ContextLoaderListener
is that it creates a WebApplicationContext
and WebApplicationContext
provides
access to the ServletContext
via ServletContextAware
beans and the getServletContext
method.
ServletContext定义了一些方法方便Servlet和Servlet容器进行通讯,在一个web应用中所有的Servlet都共用一个ServletContext,Spring在和web应用结合使用的时候,
是将Spring的容器存到ServletContext中的;而ServletContextListener用于监听ServletContext一些事件。
WebApplicationContext
. Simply delegates to
ContextLoader
as well as to
ContextCleanupListener
.
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { /** * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } /** * Close the root web application context. */ @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); }
在initWebApplicationContext里面有详细信息
if (this.context == null) { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } }
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
由最后一句可知,WeApplicationContext的实例,存放在servletContext中。

文件内容:
# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext