文档章节

从源码看spring applicationContext在web容器中加载过程

肥猫钓鱼
 肥猫钓鱼
发布于 2014/11/14 13:57
字数 1668
阅读 34
收藏 0
点赞 0
评论 0

原文:http://blog.csdn.net/fuliangliang/archive/2006/12/22/1454382.aspx

首先从WEB.XML入手

==>web.xml

代码 <context-param> <param-name>webAppRootKey</param-name> <param-value>task.root</param-value> </context-param>

<!-- 定义SPRING配置文件 -->

<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/taskContext*.xml</param-value> </context-param> </span> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param> <!-- 定义LOG4J监听器 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>

<!-- 定义SPRING监听器 -->

<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>

进入contextLoaderListener看看到底加载时做了甚么 ==>org.springframework.web.context.ContextLoaderListener

代码 public class ContextLoaderListener implements ServletContextListener {

private ContextLoader contextLoader;

/**

  • Initialize the root web application context. */ //当WEB上下文初始化时,系统会调用此方法
    public void contextInitialized(ServletContextEvent event) {
    this.contextLoader = createContextLoader();
//监听到WEB上下文初始化的时候执行SPRING上下文contextLoader的初始化工作  
this.contextLoader.initWebApplicationContext(event.getServletContext());    

}

/**

  • Create the ContextLoader to use. Can be overridden in subclasses.
  • @return the new ContextLoader */ protected ContextLoader createContextLoader() {
    return new ContextLoader();
    }

/**

  • Return the ContextLoader used by this listener. */ public ContextLoader getContextLoader() {
    return contextLoader;
    }

/**

  • Close the root web application context. */ public void contextDestroyed(ServletContextEvent event) {
    if (this.contextLoader != null) {
    this.contextLoader.closeWebApplicationContext(event.getServletContext());
    }
    }

}

看一下是怎么来初始化webapplicationContext的 ==>contextLoader.initWebApplicationContext

代码 public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
throws IllegalStateException, BeansException {

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!");
}

long startTime = System.currentTimeMillis();  
if (logger.isInfoEnabled()) {  
  logger.info("Root WebApplicationContext: initialization started");  
}  
servletContext.log("Loading Spring root WebApplicationContext");  

try {  
  // Determine parent for root web application context, if any.  
  ApplicationContext parent = loadParentContext(servletContext);  

  // Store context in local instance variable, to guarantee that  
  // it is available on ServletContext shutdown.  

  //创建web上下文  
  this.context = createWebApplicationContext(servletContext, parent);  
  servletContext.setAttribute(  
      WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);   

  if (logger.isInfoEnabled()) {  
    logger.info("Using context class [" + this.context.getClass().getName() +  
        "] for root WebApplicationContext");  
  }  
  if (logger.isDebugEnabled()) {  
    logger.debug("Published root WebApplicationContext [" + this.context +  
        "] 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;  
}  

}

==>contextLoader.createWebApplicationContext(servletContext, parent);

代码 protected WebApplicationContext createWebApplicationContext(
ServletContext servletContext, ApplicationContext parent) throws BeansException {
//根据servletContext来决定要实例化的WebApplicationContext
Class contextClass = determineContextClass(servletContext);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setParent(parent);
wac.setServletContext(servletContext);

//得到WEB.XML中设置的SPRING配置文件位置  
String configLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);  
if (configLocation != null) {  
  //把配置文件分段后设置到WebApplicationContext的ConfigLocations中  
  wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,  
      ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));  
}  
//刷新WebApplicationContext  
wac.refresh();    
return wac;  

}

==>contextLoader.determineContextClass(servletContext);

代码 protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException {
//获得需要实例化的CONTEXT类名,在web.xml中有设置,如果没有设置,那么为空
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName);
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
//如果在spring web.xml中没有设置context类位置,那么取得默认context
else {
//取得defaultStrategies配置文件中的WebApplicationContext属性
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName);
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}

SPRING上下文默认的策略是甚么呢? ==>contextLoader.defaultStrategies

代码 private static final Properties defaultStrategies;

static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
//设置classpath为contextLoader同级目录
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
//加载该目录下的所有properties文件
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}

找到同级目录下的配置文件 ==>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.

#默认的WebApplicationContext为org.springframework.web.context.support.XmlWebApplicationContext
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

==>org.springframework.web.context.support.XmlWebApplicationContext

代码 public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {

/** Default config location for the root context */

//配置了默认的spring配置文件
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

//配置文件默认BUILD路径
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

//配置文件默认后缀名
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";

/**

  • Loads the bean definitions via an XmlBeanDefinitionReader.
  • @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
  • @see #initBeanDefinitionReader
  • @see #loadBeanDefinitions */ //获得bean配置
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
    //从BEAN工厂获得一个XmlBeanDefinitionReader 来读取SPRING配置文件
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//设置beanDefinitionReader服务于当前CONTEXT  
// resource loading environment.  
beanDefinitionReader.setResourceLoader(this);  
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));  

// Allow a subclass to provide custom initialization of the reader,  
// then proceed with actually loading the bean definitions.  
initBeanDefinitionReader(beanDefinitionReader);   
//读取配置文件  
loadBeanDefinitions(beanDefinitionReader);  

}

/**

  • Initialize the bean definition reader used for loading the bean
  • definitions of this context. Default implementation is empty.
  • <p>Can be overridden in subclasses, e.g. for turning off XML validation

  • or using a different XmlBeanDefinitionParser implementation.
  • @param beanDefinitionReader the bean definition reader used by this context
  • @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setValidationMode
  • @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setDocumentReaderClass */ protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
    }

/**

  • Load the bean definitions with the given XmlBeanDefinitionReader.
  • <p>The lifecycle of the bean factory is handled by the refreshBeanFactory method;

  • therefore this method is just supposed to load and/or register bean definitions.
  • <p>Delegates to a ResourcePatternResolver for resolving location patterns

  • into Resource instances.
  • @throws org.springframework.beans.BeansException in case of bean registration errors
  • @throws java.io.IOException if the required XML document isn't found
  • @see #refreshBeanFactory
  • @see #getConfigLocations
  • @see #getResources
  • @see #getResourcePatternResolver */ //读取配置文件
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
    for (int i = 0; i < configLocations.length; i++) {
    reader.loadBeanDefinitions(configLocations[i]);
    }
    }
    }

/**

  • The default location for the root context is "/WEB-INF/applicationContext.xml",
  • and "/WEB-INF/test-servlet.xml" for a context with the namespace "test-servlet"
  • (like for a DispatcherServlet instance with the servlet-name "test"). */ //获得默认的ConfigLocations
    protected String[] getDefaultConfigLocations() {
    if (getNamespace() != null) {
    return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() +

DEFAULT_CONFIG_LOCATION_SUFFIX};
}
else {
return new String[] {DEFAULT_CONFIG_LOCATION};
}
}

==>AbstractBeanDefinitionReader.loadBeanDefinitions()

代码 public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
}

if (resourceLoader instanceof ResourcePatternResolver) {  
  // Resource pattern matching available.  
  try {  

//根据配置文件读取相应配置
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
int loadCount = loadBeanDefinitions(resources);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
}
return loadCount;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
else {
// Can only load single resources by absolute URL.
Resource resource = resourceLoader.getResource(location);
int loadCount = loadBeanDefinitions(resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}

这个是其中一个ResourceLoader的实现 ==>PathMatchingResourcePatternResolver.getResources(String locationPattern);

代码 public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
// a class path resource (multiple resources for same name possible)

  if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {  
    // a class path resource pattern  
    return findPathMatchingResources(locationPattern);  
  }  
  else {  
    // all class path resources with the given name  
    return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));  
  }  
}  
else {  
  // Only look for a pattern after a prefix here  
  // (to not get fooled by a pattern symbol in a strange prefix).  
  int prefixEnd = locationPattern.indexOf(":") + 1;  
  if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {  
    // a file pattern  
    return findPathMatchingResources(locationPattern);  
  }  
  else {  
    // a single resource with the given name  
    return new Resource[] {getResourceLoader().getResource(locationPattern)};  
  }  
}  

}

==>PathMatchingResourcePatternResolver.findPathMatchingResources(String locationPattern);

代码 protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
String rootDirPath = determineRootDir(locationPattern);
String subPattern = locationPattern.substring(rootDirPath.length());
Resource[] rootDirResources = getResources(rootDirPath);
//collectionFactory初始化一个set容量为16
Set result = CollectionFactory.createLinkedSetIfPossible(16);
for (int i = 0; i < rootDirResources.length; i++) {
Resource rootDirResource = rootDirResources[i];
if (isJarResource(rootDirResource)) {
result.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern));
}
else {
result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
}
}
if (logger.isDebugEnabled()) {
logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
}
return (Resource[]) result.toArray(new Resource[result.size()]);
}

前面说到有一个刷新WebApplicationContext的操作,但是XmlWebApplicationContext 并没有实现refresh方法,而方法的实现写在

AbstractRefreshableWebApplicationContext 中

==>AbstractRefreshableWebApplicationContext.refresh();

代码 public void refresh() throws BeansException {
if (ObjectUtils.isEmpty(getConfigLocations())) {
//设置configLocations为默认的getDefaultConfigLocations()
setConfigLocations(getDefaultConfigLocations());
}
super.refresh();
}

==>AbstractApplicationContext.refresh();

代码 public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
this.startupTime = System.currentTimeMillis();

  synchronized (this.activeMonitor) {  
    this.active = true;  
  }  

  // Tell subclass to refresh the internal bean factory.  
  refreshBeanFactory();  
  ConfigurableListableBeanFactory beanFactory = getBeanFactory();  

  // Tell the internal bean factory to use the context's class loader.  
  beanFactory.setBeanClassLoader(getClassLoader());  

  // Populate the bean factory with context-specific resource editors.  
  beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));  

  // Configure the bean factory with context semantics.  
  beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));  
  beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);  
  beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);  
  beanFactory.ignoreDependencyInterface(MessageSourceAware.class);  
  beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);  

  // Allows post-processing of the bean factory in context subclasses.  
  postProcessBeanFactory(beanFactory);  

  // Invoke factory processors registered with the context instance.  
  for (Iterator it = getBeanFactoryPostProcessors().iterator(); it.hasNext();) {  
    BeanFactoryPostProcessor factoryProcessor = (BeanFactoryPostProcessor) it.next();  
    factoryProcessor.postProcessBeanFactory(beanFactory);  
  }  

  if (logger.isInfoEnabled()) {  
    if (getBeanDefinitionCount() == 0) {  
      logger.info("No beans defined in application context [" + getDisplayName() + "]");  
    }  
    else {  
      logger.info(getBeanDefinitionCount() + " beans defined in application context [" +   

getDisplayName() + "]");
}
}

  try {  
    // Invoke factory processors registered as beans in the context.  
    invokeBeanFactoryPostProcessors();  

    // Register bean processors that intercept bean creation.  
    registerBeanPostProcessors();  

    // Initialize message source for this context.  
    initMessageSource();  

    // Initialize event multicaster for this context.  
    initApplicationEventMulticaster();  

    // Initialize other special beans in specific context subclasses.  
    onRefresh();  

    // Check for listener beans and register them.  
    registerListeners();  

    // Instantiate singletons this late to allow them to access the message source.  
    beanFactory.preInstantiateSingletons();  

    // Last step: publish corresponding event.  
    publishEvent(new ContextRefreshedEvent(this));  
  }  

  catch (BeansException ex) {  
    // Destroy already created singletons to avoid dangling resources.  
    beanFactory.destroySingletons();  
    throw ex;  
  }  
}  

}

本文转载自:http://jijiaa12345.iteye.com/blog/338185

共有 人打赏支持
肥猫钓鱼
粉丝 1
博文 52
码字总数 9287
作品 0
深圳
程序员
深入分析Spring 与 Spring MVC容器

Spring经典详解 Spring事务机制详解 Spring配置事务五种方式 关于Spring加载classpath与classpath*的过程剖析 深入分析Spring 与 Spring MVC容器 Spring系列文章 【第1章 Spring概述与结构】...

陶邦仁
2015/10/30
0
5
深入理解Spring源码(一)-IOC容器的定位,载入,注册

前言:Spring源码继承,嵌套层次非常多,读起来非常容易晕,小伙伴们在看文章的时候一定要跟着文章的思路自己去源码里点一点,看一看,并且多看几次。就会越来越清晰。下面开始正题 1.Spring...

Meet相识_bfa5
05/01
0
0
Spring 源码学习(二) IOC容器启动过程

这一节主要是记录一下Spring Ioc 容器的启动过程。 Spring 的 Ioc 容器是怎么被加载和使用的? web容器为它提供了宿主环境 ServlectContext, Tomcat 启动时会读取web.xml。 并且实例化web.x...

younchen
2014/07/10
0
0
Spring mvc 上下文初始化过程

在软件开发的中,如果某些特性的使用比较普遍,那么这些特性往往可以作为平台特性来实现,通过对这些平台特性进行有效的封装,使其向其他应用开放。正是如此,Spring由于其IOC、AOP、事务处理...

乱舞
06/29
0
0
SpringMVC加载WebApplicationContext源码分析

Spring框架提供了构建Web应用程序的全功能MVC模块,叫Spring MVC,通过Spring Core+Spring MVC即可搭建一套稳定的Java Web项目。本文通过Spring MVC源码分析介绍它的核心实现原理。 Tomcat服...

丶Lion
2015/08/29
231
0
Spring中关于bean的作用域与生命周期

在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象,除此之外,bean就与应用程序中的其他对象没有什...

忻胜霄
06/07
0
0
Spring上下文ContextLoaderListener作用

配置文件 <listener><listener-class>com.xspace.modules.sys.listener.WebContextListener</listener-class></listener> 代码 public class WebContextListener extends org.springframewor......

丶Lion
2015/08/29
0
0
向Spring大佬低头——大量源码流出解析

用Spring框架做了几年的开发,只停留在会用的阶段上,然而Spring的设计思想和原理确实一个巨大的宝库。大部分人仅仅知道怎么去配,或着加上什么属性就能达到什么效果,这些东西都可以通过查文...

Java团长17
07/11
0
0
Spring MVC 原理探秘 - 容器的创建过程

1.简介 在上一篇文章中,我向大家介绍了 Spring MVC 是如何处理 HTTP 请求的。Spring MVC 可对外提供服务时,说明其已经处于了就绪状态。再次之前,Spring MVC 需要进行一系列的初始化操作。...

coolblog.xyz
07/03
0
0
Spring 4.2 感知接口

1 ApplicationContextAware 当一个ApplicationContext创建一个实现org.springframework.context.ApplicationContextAware接口的实例时,为实例提供一个ApplicationContext引用。 public int......

Leech
2015/08/07
0
1

没有更多内容

加载失败,请刷新页面

加载更多

下一页

前端基础

1. get请求传参长度的误区 误区:我们经常说get请求参数的大小存在限制,而post请求的参数大小是无限制的。 实际上HTTP 协议从未规定 GET/POST 的请求长度限制是多少。对get请求参数的限制是...

wenxingjun
今天
0
0
Android 复制和粘贴功能

做了一回搬运工,原文地址:https://blog.csdn.net/kennethyo/article/details/76602765 Android 复制和粘贴功能,需要调用系统服务ClipboardManager来实现。 ClipboardManager mClipboardM...

她叫我小渝
今天
0
0
拦截SQLSERVER的SSL加密通道替换传输过程中的用户名密码实现运维审计(一)

工作准备 •一台SQLSERVER 2005/SQLSERVER 2008服务 •SQLSERVER jdbc驱动程序 •Java开发环境eclipse + jdk1.8 •java反编译工具JD-Core 反编译JDBC分析SQLSERVER客户端与服务器通信原理 SQ...

紅顏為君笑
今天
6
0
jQuery零基础入门——(六)修改DOM结构

《jQuery零基础入门》系列博文是在廖雪峰老师的博文基础上,可能补充了个人的理解和日常遇到的点,用我的理解表述出来,主干出处来自廖雪峰老师的技术分享。 在《零基础入门JavaScript》的时...

JandenMa
今天
0
0
linux mint 1.9 qq 安装

转: https://www.jianshu.com/p/cdc3d03c144d 1. 下载 qq 轻聊版,可在百度搜索后下载 QQ7.9Light.exe 2. 去wine的官网(https://wiki.winehq.org/Ubuntu) 安装 wine . 提醒网页可以切换成中...

Canaan_
今天
0
0
PHP后台运行命令并管理运行程序

php后台运行命令并管理后台运行程序 class ProcessModel{ private $pid; private $command; private $resultToFile = ''; public function __construct($cl=false){......

colin_86
今天
1
0
数据结构与算法4

在此程序中,HighArray类中的find()方法用数据项的值作为参数传递,它的返回值决定是否找到此数据项。 insert()方法向数组下一个空位置放置一个新的数据项。一个名为nElems的字段跟踪记录着...

沉迷于编程的小菜菜
今天
1
1
fiddler安装和基本使用以及代理设置

项目需求 由于开发过程中客户端和服务器数据交互非常频繁,有时候服务端需要知道客户端调用接口传了哪些参数过来,这个时候就需要一个工具可以监听这些接口请求参数,已经接口的响应的数据,这种...

银装素裹
今天
0
0
Python分析《我不是药神》豆瓣评论

读取 Mongo 中的短评数据,进行中文分词 对分词结果取 Top50 生成词云 生成词云效果 看来网上关于 我不是药神 vs 达拉斯 的争论很热啊。关于词频统计就这些,代码中也会完成一些其它的分析任...

猫咪编程
今天
0
0
虚拟机怎么安装vmware tools

https://blog.csdn.net/tjcwt2011/article/details/72638977

AndyZhouX
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部