在开发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明明不为空,可是断点调试却不会执行,不知道哪位能解释一下。

简单介绍Spring的ContextLoaderListener的更多相关文章

  1. 简单介绍Spring是什么?

    对于面试者回答什么是Spring,这个问题占6分分值,分值点分布:1.Spring的核心是一个轻量级(Lightweight)的容器(Container).2.Spring是实现IoC(Inversi ...

  2. Spring Framework简单介绍

    Spring Framework        学习java编程不知不觉已经三年时间了,開始的时候,总是喜欢看着视频,然后按部就班的敲打着键盘,每当系统正常执行后.心里乐开了花.最開始的时候,所有的代 ...

  3. 从头认识Spring-1.14 SpEl表达式(1)-简单介绍与嵌入值

    这一章节我们来讨论一下SpEl表达式的简单介绍与嵌入值. 1.SpEl表达式简单介绍 Spring Excpression Language (SpEL)语言支持在执行时操作和查询对象 事实上就是在执 ...

  4. 小代介绍Spring Boot

    想要获取更多文章可以访问我的博客 - 代码无止境. 小代很顺利的完成了陈BOSS交代给他搭建Spring Boot示例程序的任务.但是小代是一个乐于学习的程序员,他通过一番学习总结了一篇简单介绍Spr ...

  5. Spring Cache简单介绍和使用

    Spring Cache 缓存是实际工作中非经常常使用的一种提高性能的方法, 我们会在很多场景下来使用缓存. 本文通过一个简单的样例进行展开,通过对照我们原来的自己定义缓存和 spring 的基于凝视 ...

  6. 第一次玩博客,今天被安利了一个很方便JDBC的基于Spring框架的一个叫SimpleInsert的类,现在就来简单介绍一下

    首先先对这段代码的简单介绍,我之前在需要操作JDBC的时候总是会因为经常要重新写SQL语句感到很麻烦.所以就能拿则拿不能拿的就简单地封装了一下. 首先是Insert.Spring框架的JDBC包里面的 ...

  7. 请简单介绍一下Spring

    Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架. Spring ...

  8. spring cloud之简单介绍

    以下是来自官方的一篇简单介绍: spring Cloud provides tools for developers to quickly build some of the common patte ...

  9. Spring进阶之路(10)-Advice简单介绍以及通过cglib生成AOP代理对象

    Advice简单介绍 1. Before:在目标方法运行之前运行织入.假设Before的处理中没有进行特殊的处理.那么目标方法终于会运行,可是假设想要阻止目标方法运行时.能够通过抛出一个异常来实现.B ...

随机推荐

  1. JAVA类和对象创建

    面向对象 学习目标: 理解面向对象的编程思想 理解类与对象的关系 如何创建类与对象 方法重载 一:什么是面向对象编程(OOP) 面向对象编程(Object Oriented Programming,O ...

  2. tryparse

    [C#笔札]Tryparse的用法   这是参考读物的上得一个例子.自己仿照做的作业 private void button1_Click(object sender, EventArgs e) { ...

  3. Shiny+SQLite打造轻量级网页应用

    参考: R语言核心技能:交互式展示Shiny  中文 R语言用Shiny包快速搭建交互网页应用  R七种武器之交互化展示包shiny 用R的shiny包写一个基因的ID转换小程序 https://gi ...

  4. vue.js 过渡&动画

    9-17 在add ,update, remove DOM时 提供多种方式的应用过度效果. 包括以下可选工具:(2大类,css和js) 在css过度和动画中自动应用class 配合使用第三方css动画 ...

  5. codeforces 930b//Game with String// Codeforces Round #468 (Div. 1)

    题意:一个串,右循环移位后,告诉你第一个字母,还能告诉你一个,问你能确定移位后的串的概率. 用map记录每个字母出现的位置.对于每个字母,用arr[j][k]记录它的所有出现位置的后j位是字母k的个数 ...

  6. codeforces 993c//Careful Maneuvering// Codeforces Round #488 by NEAR (Div. 1)

    题意:x轴-100和+100的有敌人飞船,纵坐标由输入数据给出,我方有2飞船在x轴0,y坐标待定.0时刻时敌人同时向我方2飞船发出光线,光线会穿透飞船打到敌人自己,问2飞船放在哪敌人损失最大? 假如- ...

  7. Skills CodeForces - 614D (贪心)

    链接 大意: $n$门课, 第$i$门分数$a_i$, 可以增加共$m$分, 求$cnt_{mx}*cf+mi*cm$的最大值 $cnt_{mx}$为满分的科目数, $mi$为最低分, $cf$, $ ...

  8. service几种访问类型(集群外负载均衡访问LoadBalancer , 集群内访问ClusterIP,VPC内网负载均衡LoadBalancer ,集群外访问NodePort)

    一.集群外访问(负载均衡) kind: ServiceapiVersion: v1spec: ports: - protocol: TCP port: 4341 targetPort: 8080 no ...

  9. SSH 反向代理

    SSH反向代理 被控制端没有NAT或者没有静态公网IP,把本端一台服务器映射到外网给远端SSH进来,建立SSH反向隧道. 先映射本端机器到外网  nat server 2222to22 protoco ...

  10. Netty高性能编程备忘录(下)

    估计很快就要被拍砖然后修改,因此转载请保持原文链接,否则视为侵权... http://calvin1978.blogcn.com/articles/netty-performance.html 前文再 ...