http://blog.csdn.net/qq924862077/article/details/52769754
1<context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value> 4 classpath:applicationContext.xml 5 </param-value> 6</context-param> 7<listener> 8 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 9</listener>
在tomcat启动时,spring通过上述配置会初始化spring容器,注入applicationContext.xml中配置的bean以及其他一些配置。
1public class ContextLoaderListener extends ContextLoader implements ServletContextListener { 2 3 public ContextLoaderListener() { 4 } 5 public ContextLoaderListener(WebApplicationContext context) { 6 super(context); 7 } 8 @Override 9 public void contextInitialized(ServletContextEvent event) { 10 initWebApplicationContext(event.getServletContext()); 11 } 12 @Override 13 public void contextDestroyed(ServletContextEvent event) { 14 closeWebApplicationContext(event.getServletContext()); 15 ContextCleanupListener.cleanupAttributes(event.getServletContext()); 16 } 17}
ContextLoderListener实现ServletContextListener接口,而该接口继承java的监听标记接口EventListener,表示当servlet容器启动时,就会接受通知,进而进行一系列的初始化操作。
1public interface ServletContextListener extends EventListener { 2 3 /** 4 * Receives notification that the web application initialization 5 * process is starting. 6 * 7 * <p>All ServletContextListeners are notified of context 8 * initialization before any filters or servlets in the web 9 * application are initialized. 10 * 11 * @param sce the ServletContextEvent containing the ServletContext 12 * that is being initialized 13 */ 14 public void contextInitialized(ServletContextEvent sce); 15 16 /** 17 * Receives notification that the ServletContext is about to be 18 * shut down. 19 * 20 * <p>All servlets and filters will have been destroyed before any 21 * ServletContextListeners are notified of context 22 * destruction. 23 * 24 * @param sce the ServletContextEvent containing the ServletContext 25 * that is being destroyed 26 */ 27 public void contextDestroyed(ServletContextEvent sce); 28}
spring的具体初始化工作均在父类ContextLoder中进行,具体初始化步骤如下:
-
判断是否已经存在WebApplicationContext(spring容器),如果存在,则抛出异常。
-
创建WebApplicationContext容器,容web.xml中获取context-param名称为contextClass的value,该类必须实现WebApplicationContext接口,如果没有指定,则默认使用xmlWebApplicationContext。
-
判断创建的WebApplicationContext容器是否为ConfigurableApplicationContext的实例或子类,如果是,则判断该容器是否至少刷新一次并且还没有关闭(是否有效),如果无效,则重新设置容器的id,并加载对应的contextConfigLocation配置(spring配置), 加载父容器,spring提供一个模板方法,如果需要配置父容器,可以继承ContextLoder,并覆盖loadParentContext方法。
-
线程绑定容器
/** * Initialize Spring's web application context for the given servlet context, * using the application context provided at construction time, or creating a new one * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params. * @param servletContext current servlet context * @return the new WebApplicationContext * @see #ContextLoader(WebApplicationContext) * @see #CONTEXT_CLASS_PARAM * @see #CONFIG_LOCATION_PARAM / 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!"); }
1 Log logger = LogFactory.getLog(ContextLoader.class); 2 servletContext.log("Initializing Spring root WebApplicationContext"); 3 if (logger.isInfoEnabled()) { 4 logger.info("Root WebApplicationContext: initialization started"); 5 } 6 long startTime = System.currentTimeMillis(); 7 8 try { 9 // Store context in local instance variable, to guarantee that 10 // it is available on ServletContext shutdown. 11 if (this.context == null) { 12 //创建容器 13 this.context = createWebApplicationContext(servletContext); 14 } 15 if (this.context instanceof ConfigurableWebApplicationContext) { 16 ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; 17 if (!cwac.isActive()) { 18 // The context has not yet been refreshed -> provide services such as 19 // setting the parent context, setting the application context id, etc 20 if (cwac.getParent() == null) { 21 // The context instance was injected without an explicit parent -> 22 // determine parent for root web application context, if any. 23 ApplicationContext parent = loadParentContext(servletContext); 24 cwac.setParent(parent); 25 } 26 //如果容器无效,则重置contextId,且重新加载contextConfigLocation配置 27 configureAndRefreshWebApplicationContext(cwac, servletContext); 28 } 29 } 30 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); 31 //线程绑定容器context 32 ClassLoader ccl = Thread.currentThread().getContextClassLoader(); 33 if (ccl == ContextLoader.class.getClassLoader()) { 34 currentContext = this.context; 35 } 36 else if (ccl != null) { 37 currentContextPerThread.put(ccl, this.context); 38 } 39 40 if (logger.isDebugEnabled()) { 41 logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + 42 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); 43 } 44 if (logger.isInfoEnabled()) { 45 long elapsedTime = System.currentTimeMillis() - startTime; 46 logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); 47 } 48 49 return this.context; 50 } 51 catch (RuntimeException ex) { 52 logger.error("Context initialization failed", ex); 53 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); 54 throw ex; 55 } 56 catch (Error err) { 57 logger.error("Context initialization failed", err); 58 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); 59 throw err; 60 } 61}