在開發Spring的Web項目中,通常我們都會在web.xml中配置一個Spring的核心監聽器,就是把Spring的IOC容器納入Servlet容器中,配置如下:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
查看ContextLoaderListener源碼如下:
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { public ContextLoaderListener() {} public ContextLoaderListener(WebApplicationContext context) { super(context); } @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }
ContextLoaderListener官方源碼定義是Spring的root(也就是WebApplicationContext)啟動和關閉的引導監聽器,當調用ContextLoaderListener的無參構造器時,就會創建一個新的ContextLoaderListener,也將會創建一個web應用上下文基於web.xml中的contextLoader和contextConfigLocation的servlet context-param參數,創建的應用上下文會被注冊到ServletContext中通過WebApplicationContext裡的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE這個屬性。
ContextLoaderListener繼承自ContextLoader並且實現了ServletContextListener接口,實現ServletContextListener作用不言而喻,就是要讓Spring和Servlet容器關聯起來,讓Spring容器伴隨著Servlet容器的啟動而啟動,其實這個類中最主要的一個方法就是contextInitialized(),作用就是Spring上下文初始化,裡面的initWebApplicationContext()是從父類ContextLoader中繼承過來的,查看源碼:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. 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); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
關於多次出現的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE這個參數,我個人理解的就是它是Servlet容器識別Spring的一個標識,如果為null,說明Spring還有沒注冊進Servlet容器中,
緊接著就是創建WebApplicationContext,configureAndRefreshWebApplicationContext()這個方法最主要就是配置applicationContext.xml這個文件,
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);這句代碼就是把Spring容器注冊進ServletContext中。
關於WebApplicationContext這個接口:
public interface WebApplicationContext extends ApplicationContext { String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; String SCOPE_REQUEST = "request"; String SCOPE_SESSION = "session"; String SCOPE_GLOBAL_SESSION = "globalSession"; String SCOPE_APPLICATION = "application"; String SERVLET_CONTEXT_BEAN_NAME = "servletContext"; String CONTEXT_PARAMETERS_BEAN_NAME = "contextParameters"; String CONTEXT_ATTRIBUTES_BEAN_NAME = "contextAttributes"; ServletContext getServletContext(); }
WebApplicationContext繼承自ApplicationContext,這個接口添加了一個getServletContext()方法,並且定義了一些root context在啟動進程中必須綁定的application屬性,和一般的應用上下文一樣,web application contexts也是分層的,每一個應用都有一個root context,並且應用裡的每個Servlet都有自己的子context,除了標准的應用上下文聲明周期,WebApplicationContext實現需要探測ServletContextAware beans和調用setServletContext()方法。
WebApplicationContext裡面定義了一些常用的bean作用域屬性,比如request,session,globalSession,application,servletContext.
其實可以在相應的類中打斷點調試,這樣更能加深印象,有一點不明白的是
else if (ccl != null) { currentContextPerThread.put(ccl, this.context); }
這段代碼中ccl明明不為空,可是斷點調試卻不會執行,不知道哪位能解釋一下。