ContextLoaderListener容器初始化

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中进行,具体初始化步骤如下:

  1. 判断是否已经存在WebApplicationContext(spring容器),如果存在,则抛出异常。

  2. 创建WebApplicationContext容器,容web.xml中获取context-param名称为contextClass的value,该类必须实现WebApplicationContext接口,如果没有指定,则默认使用xmlWebApplicationContext。

  3. 判断创建的WebApplicationContext容器是否为ConfigurableApplicationContext的实例或子类,如果是,则判断该容器是否至少刷新一次并且还没有关闭(是否有效),如果无效,则重新设置容器的id,并加载对应的contextConfigLocation配置(spring配置), 加载父容器,spring提供一个模板方法,如果需要配置父容器,可以继承ContextLoder,并覆盖loadParentContext方法。

  4. 线程绑定容器

    /** * 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}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )