http://blog.csdn.net/qq924862077/article/details/52769754

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

在tomcat启动时,spring通过上述配置会初始化spring容器,注入applicationContext.xml中配置的bean以及其他一些配置

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());
}
}

ContextLoderListener实现ServletContextListener接口,而该接口继承java的监听标记接口EventListener,表示当servlet容器启动时,就会接受通知,进而进行一系列的初始化操作。

public interface ServletContextListener extends EventListener {

    /**
* Receives notification that the web application initialization
* process is starting.
*
* <p>All ServletContextListeners are notified of context
* initialization before any filters or servlets in the web
* application are initialized.
*
* @param sce the ServletContextEvent containing the ServletContext
* that is being initialized
*/
public void contextInitialized(ServletContextEvent sce); /**
* Receives notification that the ServletContext is about to be
* shut down.
*
* <p>All servlets and filters will have been destroyed before any
* ServletContextListeners are notified of context
* destruction.
*
* @param sce the ServletContextEvent containing the ServletContext
* that is being destroyed
*/
public void contextDestroyed(ServletContextEvent sce);
}
    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!");
} 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);
}
//如果容器无效,则重置contextId,且重新加载contextConfigLocation配置
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
//线程绑定容器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;
}
}

ContextLoaderListener容器初始化的更多相关文章

  1. springMVC源码分析--容器初始化(一)ContextLoaderListener

    在spring Web中,需要初始化IOC容器,用于存放我们注入的各种对象.当tomcat启动时首先会初始化一个web对应的IOC容器,用于初始化和注入各种我们在web运行过程中需要的对象.当tomc ...

  2. SpringMVC源码分析--容器初始化(四)FrameworkServlet

    在上一篇博客SpringMVC源码分析--容器初始化(三)HttpServletBean我们介绍了HttpServletBean的init函数,其主要作用是初始化了一下SpringMVC配置文件的地址 ...

  3. 【Spring源码解析】—— 结合SpringMVC过程理解IOC容器初始化

    关于IOC容器的初始化,结合之前SpringMVC的demo,对其过程进行一个相对详细的梳理,主要分为几个部分: 一.IOC的初始化过程,结合代码和debug过程重点说明 1. 为什么要debug? ...

  4. Web容器初始化过程

    一.SpringMVC启动过程 Spring的MVC是基于Servlet功能实现的,每个web工程中都有一个web.xml文件,web容器在启动的时候会加载这个配置文件,当一个web应用加载到web容 ...

  5. springmvc web.xml配置之 -- SpringMVC IOC容器初始化

    SpringMVC IOC容器初始化 首先强调一下SpringMVC IOC容器初始化有些特别,在SpringMVC中除了生成一个全局的spring Ioc容器外,还会为DispatcherServl ...

  6. Spring容器初始化的时候如何添加一个定时器?

    昨天遇到这个问题,在项目启动的时候添加一个定时器隔一段时间扫描有没有定时发送的邮件(当然也可以是你自己的业务逻辑),也在网上找了资料,加上自己的修改,终于成功了.所以来做个记录. 1.ServletC ...

  7. Servlet容器初始化IOC容器

    <!-- ServletContext参数,配置Ioc容器的xml文件名 --> <context-param> <param-name>contextConfig ...

  8. SpringMVC源码学习:容器初始化+MVC初始化+请求分发处理+参数解析+返回值解析+视图解析

    目录 一.前言 二.初始化 1. 容器初始化 根容器查找的方法 容器创建的方法 加载配置文件信息 2. MVC的初始化 文件上传解析器 区域信息解析器 handler映射信息解析 3. Handler ...

  9. Spring IoC容器初始化过程学习

    IoC容器是什么?IoC文英全称Inversion of Control,即控制反转,我么可以这么理解IoC容器: 把某些业务对象的的控制权交给一个平台或者框架来同一管理,这个同一管理的平台可以称为I ...

随机推荐

  1. Java内存区域与模拟内存区域异常

    我把Java的内存区域画了一张思维导图,以及各区域的主要功能. 模拟Java堆溢出 Java堆用于存储对象实例.仅仅要不断地创建对象而且保证GC ROOTS到对象之间有可达路径避免被回收机制清除.就能 ...

  2. xss跨站脚本攻击与防御读书笔记(原创)

    XSS在客户端执行 可以任意执行js代码 0x01  xss 的利用方式 1. 钓鱼      案例:http://www.wooyun.org/bugs/wooyun-2014-076685  我是 ...

  3. jsp中jquery用法一步刷新 验证用户名是否存在

    <script type="text/javascript"> /* $(document).ready(function(){ var id="ha&quo ...

  4. beforeRouteLeave 实现vue路由拦截浏览器的需求,进行一系列操作 草稿保存等等

    场景:为了防止用户失误点错关闭按钮等等,导致没有保存已输入的信息(关键信息).用法://在路由组件中: beforeRouteLeave (to, from, next) { if(用户已经输入信息) ...

  5. poj1649 Rescue(BFS+优先队列)

    Rescue Time Limit: 2 Seconds      Memory Limit: 65536 KB Angel was caught by the MOLIGPY! He was put ...

  6. Easy UI form表单提交 IE浏览器不执行success ,以及 datagrid 展示过慢

    最近在做一个Easy ui的项目 发现了一些问题,在这里总结下 1.表单提交,后端代码 public ActionResult Save(Request model) { ResultInfo _in ...

  7. c++引用返回值

    引用作为函数的返回值时,函数的返回值能够理解为函数返回了一个变量(事实上,函数返回引用时,它返回的是一个指向返回值的隐式指针),因此,值为引用的函数能够用作赋值运算符的左操作数.另外,用引用返回一个函 ...

  8. 关于proplists:get_value/2 与lists:keyfind/3 的效率比较

    关于proplists:get_value/2 与lists:keyfind/2 的效率 早有比较,已出结论,lists:keyfind/2 的效率要好很多,好些人都是直接用或者做过它们之间的比较测试 ...

  9. ThinkPHP学习笔记(二)

    1.比较好的参考手册(非官方,注意:也有一些错误,当出不来想要的效果时以官方的手册为准):http://www.5idev.com/p-thinkphp_lib_vendor.shtml 2.加载自定 ...

  10. UIScrollView奇葩不滑动

    首先要说声尼玛,真奇葩,从来都没有遇到过这个问题,首先描述一下背景: 我是用XIB拖拽了一个UIScrollView在View上,然后设置了frame,在ViewDidLoad里面,设置了scroll ...