参考网址:http://blog.csdn.net/ysughw/article/details/8992322

ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。至于ApplicationContext.xml这个配置文件部署在哪,如何配置多个xml文件,现在的方法就是查看它的API文档。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。看看它的API说明。

类ContextLoader api原文:

Performs the actual initialization work for the root application context. Called by ContextLoaderListener.

Looks for a "contextClass" parameter at the web.xml context-param level to specify the context class type, falling back to the default of XmlWebApplicationContext if not found. With the default ContextLoader implementation, any context class specified needs to implement the ConfigurableWebApplicationContext interface.

Processes a "contextConfigLocation" context-param and passes its value to the context instance, parsing it into potentially multiple file paths which can be separated by any number of commas and spaces, e.g. "WEB-INF/applicationContext1.xml, WEB-INF/applicationContext2.xml". Ant-style path patterns are supported as well, e.g. "WEB-INF/*Context.xml,WEB-INF/spring*.xml" or "WEB-INF/**/*Context.xml". If not explicitly specified, the context implementation is supposed to use a default location (with XmlWebApplicationContext: "/WEB-INF/applicationContext.xml").

第一段说明ContextLoader的作用--它为初始化工作装配请求上下文,这是由于调用ContextLoaderListener触发的。

第二段,ContextLoader将在web.xml寻找contextClass参数,它是上下文的class类型,默认的是XmlWebApplicationContext

第三段,讲如何部署applicationContext的xml文件。

如果在web.xml中不写任何参数配置信息,默认的路径是/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml;

如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:
<context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            /WEB-INF/classes/applicationContext-*.xml   
        </param-value>  
    </context-param>  
在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。上面的applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。

相应源码:

在类ContextLoader中的声明:

public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";

由于ContextLoader的默认上下文是XmlWebApplicationContext,在XmlWebApplicationContext中的声明:

public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

由此可见applicationContext.xml的文件位置就可以有两种默认实现:

第一种:直接将之放到/WEB-INF下,之在web.xml中声明一个listener;

第二种:将之放到classpath下,但是此时要在web.xml中加入<context-param>,用它来指明你的applicationContext.xml的位置以供web容器来加载。按照Struts2 整合spring的官方给出的档案,写成:
<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> 
</context-param>

附:从源码解析ContextLoaderListener、ContextLoader的主要作用

ContextLoaderListener源码

public class ContextLoaderListener extends ContextLoader implements
ServletContextListener {
private ContextLoader contextLoader; .....
//初始化上下文
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
//调用父类的initWebApplicationContext方法
this.contextLoader.initWebApplicationContext(event.getServletContext());
} }

ContextLoader源码

public class ContextLoader {
public static final String CONTEXT_CLASS_PARAM = "contextClass";
public static final String CONTEXT_ID_PARAM = "contextId";
public static final String CONTEXT_INITIALIZER_CLASSES_PARAM = "contextInitializerClasses";
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
public static final String LOCATOR_FACTORY_SELECTOR_PARAM = "locatorFactorySelector";
public static final String LOCATOR_FACTORY_KEY_PARAM = "parentContextKey";
private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
private static final Properties defaultStrategies;
private static final Map<ClassLoader, WebApplicationContext> currentContextPerThread;
private static volatile WebApplicationContext currentContext;
private WebApplicationContext context;
private BeanFactoryReference parentContextRef; //加载ContextLoader.properties
static {
try {
ClassPathResource resource = new ClassPathResource(
"ContextLoader.properties", ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException ex) {
throw new IllegalStateException(
"Could not load 'ContextLoader.properties': "
+ ex.getMessage());
} currentContextPerThread = new ConcurrentHashMap(1);
} ......
//初始化WebApplicationContext
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 {
//如果WebApplicationContext为空,则创建。
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
configureAndRefreshWebApplicationContext(
(ConfigurableWebApplicationContext) this.context,
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;
}
}
//创建WebApplicationContext
protected WebApplicationContext createWebApplicationContext(
ServletContext sc) {
Class contextClass = determineContextClass(sc);
if (!(ConfigurableWebApplicationContext.class
.isAssignableFrom(contextClass))) {
throw new ApplicationContextException("Custom context class ["
+ contextClass.getName() + "] is not of type ["
+ ConfigurableWebApplicationContext.class.getName() + "]");
}
ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils
.instantiateClass(contextClass);
return wac;
} ...... //配置、刷新WebApplicationContext
protected void configureAndRefreshWebApplicationContext(
ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
String idParam = sc.getInitParameter("contextId");
if (idParam != null) {
wac.setId(idParam);
} else if ((sc.getMajorVersion() == 2)
&& (sc.getMinorVersion() < 5)) {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
+ ObjectUtils.getDisplayString(sc
.getServletContextName()));
} else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
+ ObjectUtils.getDisplayString(sc.getContextPath()));
} } ApplicationContext parent = loadParentContext(sc); wac.setParent(parent);
wac.setServletContext(sc);
String initParameter = sc.getInitParameter("contextConfigLocation");
if (initParameter != null) {
wac.setConfigLocation(initParameter);
}
customizeContext(sc, wac);
wac.refresh();
}
//确认上下文class类型
protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext
.getInitParameter("contextClass");
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName,
ClassUtils.getDefaultClassLoader());
} catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class ["
+ contextClassName + "]", ex);
}
}
//contextClassName默认值:org.springframework.web.context.support.XmlWebApplicationContext
contextClassName = defaultStrategies
.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName,
ContextLoader.class.getClassLoader());
} catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName
+ "]", ex);
}
} ......
}
ContextLoader.properties
# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

从上面的源码可以得知:类ContextLoaderListener主要的作用是初始化上下文WebApplicationContext(接口)的实现类:org.springframework.web.context.support.XmlWebApplicationContext。

此外,在类ContextLoader中,方法configureAndRefreshWebApplicationContext用于部署contextConfigLocation。

ContextLoaderListener作用详解的更多相关文章

  1. ContextLoaderListener作用详解(转)

    ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息.因为它实现了ServletContextListener这个接口,在 ...

  2. Linux(centos)系统各个目录的作用详解

    Linux(centos)系统各个目录的作用详解 文件系统的类型 LINUX有四种基本文件系统类型:普通文件.目录文件.连接文件和特殊文件,可用file命令来识别. 普通文件:如文本文件.C语言元代码 ...

  3. shell脚本中常见的一些特殊符号和作用详解

    这篇文章主要介绍了shell脚本中常见的一些特殊符号和它的作用详解,总结的很简洁,容易看懂,需要的朋友可以参考下   在编写Shell脚本时,我们需要会用到各种各样的特殊符号,通过这些特殊符号可以使我 ...

  4. linux(CENTOS)系统各个目录的作用详解

    Linux(CentOS)系统各个目录的作用详解 文件的类型 LINUX有四种基本文件系统类型:普通文件.目录文件.连接文件和特殊文件,可用file命令来识别. 普通文件:如文本文件.C语言元代码.S ...

  5. MySQL中的主键,外键有什么作用详解

    MySQL中的主键,外键有什么作用详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 学关系型数据库的同学,尤其在学习主键和外键时会产生一定的困惑.那么今天我们就把这个困惑连根拔起 ...

  6. Python中__init__.py文件的作用详解

    转自http://www.jb51.net/article/92863.htm Python中__init__.py文件的作用详解 http://www.jb51.net/article/86580. ...

  7. jsp九大内置对象和其作用详解

    jsp九大内置对象和其作用详解 JSP中一共预先定义了9个这样的对象,分别为:request.response.session.application.out.pagecontext.config.p ...

  8. [转载]java中import作用详解

    [转载]java中import作用详解 来源: https://blog.csdn.net/qq_25665807/article/details/74747868 这篇博客讲的真的很清楚,这个作者很 ...

  9. C++中头文件与源文件的作用详解

    一.C++ 编译模式 通常,在一个 C++ 程序中,只包含两类文件―― .cpp 文件和 .h 文件.其中,.cpp 文件被称作 C++ 源文件,里面放的都是 C++ 的源代码:而 .h 文件则被称作 ...

随机推荐

  1. dedecms5.7文章实现阅读全文功能二次开发

    阅读全文功能其实在很多的流行站点都有的,比如网易,新浪等,随着文章内容的增加,当一个页面有多个分页的时候,就会显示出这个“在本页阅读全文”的链接,点击这个链接之后,出现的,将是这篇文章以没有分页出现的 ...

  2. 001.android初级篇之ToolBar

    官方的最新support library v7中提供了新的组件ToolBar,用来替代之前的ActionBar,实现更为弹性的设计在 material design 也对之做了名称的定义:App ba ...

  3. js格式化日期,获取当月的第一天,与最后一天.

    //格式化日期 function setDate(date){   y=date.getFullYear();   m=date.getMonth()+1;   d=date.getDate();   ...

  4. 第一个Cocos2d-x Lua游戏

    我们的编写的第一个Cocos2d-x Lua程序,命名为HelloLua,从该工程开始学习其它的内容.创建工程我们创建Cocos2d-x Lua工程可以通过Cocos2d-x提供的命令工具cocos实 ...

  5. iOS数据持久化(二)SQLite

    一.什么是SQLite SQLite是一款轻型的嵌入式数据库,它占用资源非常的低,处理速度快,非常适合用于移动端开发. 二.使用 创建DataBaseHandle.h   &    DataB ...

  6. C 【block类型全方位详解】

    ------------------------------------------- block变量的概念 #import <Foundation/Foundation.h> int m ...

  7. iOS-GCD多线程

    GCD GCD -- Grand Central Dispatch 是基于C语言的底层API 用Block定义任务,将任务添加到线程中使用.集中管理 1.GCD的执行函数 //同步 dispatch_ ...

  8. 一个线程间的通讯小程序__(Java_Thread_Inout.Output)

    //多线程通讯 //多个线程处理同一资源,但是任务不同 //等待唤醒方法: //wait():将线程变成为冻结状态,线程会被存储在线程池中; //notify():唤醒线程中的一个线程(任意的) // ...

  9. 在Android项目中调用已有.so库

    注意该.so库指的是android平台的,非一般linux.unix平台:1.现有库libcom_ycan_testLib.so2.新建android项目TestLib23.添加新类:类名:testL ...

  10. 《Linux系统 date、cal、hwclock时间命令的用法》

    date命令的用法: [root@apache ~]# date //查看当前系统的时间 Sat Jun 14 13:46:02 CST 2014 [root@apache ~]# date -s & ...