`
hotforcc
  • 浏览: 61093 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring Open Sourse Research(ContextLoaderListener Parts)

阅读更多
Spring 源码分析(ContextLoaderListener Parts)
ContextLoaderListener .java
java 代码
  1.   
  2. public class ContextLoaderListener implements ServletContextListener {   
  3.   
  4.     private ContextLoader contextLoader;   
  5.   
  6.   
  7.     /**  
  8.      * Initialize the root web application context.  
  9.      */  
  10.     public void contextInitialized(ServletContextEvent event) {   
  11.         this.contextLoader = createContextLoader();   
  12.         this.contextLoader.initWebApplicationContext(event.getServletContext());   
  13.     }   
  14.   
  15.     /**  
  16.      * Create the ContextLoader to use. Can be overridden in subclasses.  
  17.      * @return the new ContextLoader  
  18.      */  
  19.     protected ContextLoader createContextLoader() {   
  20.         return new ContextLoader();   
  21.     }   
  22.   
  23.     /**  
  24.      * Return the ContextLoader used by this listener.  
  25.      * @return the current ContextLoader  
  26.      */  
  27.     public ContextLoader getContextLoader() {   
  28.         return this.contextLoader;   
  29.     }   
  30.   
  31.   
  32.     /**  
  33.      * Close the root web application context.  
  34.      */  
  35.     public void contextDestroyed(ServletContextEvent event) {   
  36.         if (this.contextLoader != null) {   
  37.             this.contextLoader.closeWebApplicationContext(event.getServletContext());   
  38.         }   
  39.     }   
  40.   
  41. }   
  42.   

2ContectLoader.java
//初始化工作,调用默认策略DEFAULT_STRATEGIES_PATH
java 代码
  1. static {   
  2.     // Load default strategy implementations from properties file.   
  3.     // This is currently strictly internal and not meant to be customized   
  4.     // by application developers.   
  5.     try {   
  6.         ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);   
  7.         defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);   
  8.     }   
  9.     catch (IOException ex) {   
  10.         throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());   
  11.     }   
  12. }   
调用默认策略DEFAULT_STRATEGIES_PATH
Spring在web环境下会默认初始化XmlWebApplicationContext这个

defaultStrategies:
java 代码
  1. # Default WebApplicationContext implementation class for ContextLoader.   
  2. # Used as fallback when no explicit context implementation has been specified as context-param.   
  3. # Not meant to be customized by application developers.   
  4.   
  5. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext   
  6.   
  7.   
  8. this.contextLoader.initWebApplicationContext(event.getServletContext());  

 初始化工作
java 代码
  1. /**  
  2.     * Initialize Spring's web application context for the given servlet context,  
  3.     * according to the "contextClass" and "contextConfigLocation" context-params.  
  4.     * @param servletContext current servlet context  
  5.     * @return the new WebApplicationContext  
  6.     * @throws IllegalStateException if there is already a root application context present  
  7.     * @throws BeansException if the context failed to initialize  
  8.     * @see #CONTEXT_CLASS_PARAM  
  9.     * @see #CONFIG_LOCATION_PARAM  
  10.     */  
  11.    public WebApplicationContext initWebApplicationContext(ServletContext servletContext)   
  12.            throws IllegalStateException, BeansException {   
  13.   
  14.        if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {   
  15.            throw new IllegalStateException(   
  16.                    "Cannot initialize context because there is already a root application context present - " +   
  17.                    "check whether you have multiple ContextLoader* definitions in your web.xml!");   
  18.        }   
  19.   
  20.        servletContext.log("Initializing Spring root WebApplicationContext");   
  21.        if (logger.isInfoEnabled()) {   
  22.            logger.info("Root WebApplicationContext: initialization started");   
  23.        }   
  24.        long startTime = System.currentTimeMillis();   
  25.   
  26.        try {   
  27.            // Determine parent for root web application context, if any.   
  28.            ApplicationContext parent = loadParentContext(servletContext);   
  29.   
  30.            // Store context in local instance variable, to guarantee that   
  31.            // it is available on ServletContext shutdown.   
  32.            this.context = createWebApplicationContext(servletContext, parent);   
  33.            servletContext.setAttribute(   
  34.                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);   
  35.   
  36.            if (logger.isDebugEnabled()) {   
  37.                logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +   
  38.                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");   
  39.            }   
  40.            if (logger.isInfoEnabled()) {   
  41.                long elapsedTime = System.currentTimeMillis() - startTime;   
  42.                logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");   
  43.            }   
  44.   
  45.            return this.context;   
  46.        }   
  47.        catch (RuntimeException ex) {   
  48.            logger.error("Context initialization failed", ex);   
  49.            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);   
  50.            throw ex;   
  51.        }   
  52.        catch (Error err) {   
  53.            logger.error("Context initialization failed", err);   
  54.            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);   
  55.            throw err;   
  56.        }   
  57.    }   

 initWebApplicationContext()调用了createWebApplicationContext()
java 代码
  1. /**  
  2.     * Instantiate the root WebApplicationContext for this loader, either the  
  3.     * default context class or a custom context class if specified.  
  4.     * This implementation expects custom contexts to implement  
  5.     * ConfigurableWebApplicationContext. Can be overridden in subclasses.  
  6.     * @param servletContext current servlet context  
  7.     * @param parent the parent ApplicationContext to use, or null if none  
  8.     * @return the root WebApplicationContext  
  9.     * @throws BeansException if the context couldn't be initialized  
  10.     * @see ConfigurableWebApplicationContext  
  11.     */  
  12.    protected WebApplicationContext createWebApplicationContext(   
  13.            ServletContext servletContext, ApplicationContext parent) throws BeansException {   
  14.        //取得代用的从Context Class ,WebApplicationContext default   
  15.        Class contextClass = determineContextClass(servletContext);   
  16.           
  17.        //判断contextClass是否是ConfigurableWebApplicationContext的子类,如果不是,throws ApplicationContextException   
  18.        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {   
  19.            throw new ApplicationContextException("Custom context class [" + contextClass.getName() +   
  20.                    "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");   
  21.        }   
  22.        //初始化这个类   
  23.        ConfigurableWebApplicationContext wac =   
  24.                (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);   
  25.        wac.setParent(parent);   
  26.        wac.setServletContext(servletContext);   
  27.        String configLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);   
  28.        if (configLocation != null) {   
  29.            wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,   
  30.                    ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));   
  31.        }   
  32.   
  33.        wac.refresh();   
  34.        return wac;   
  35.    }   

    
java 代码
  1. /**  
  2.  * Return the WebApplicationContext implementation class to use, either the  
  3.  * default XmlWebApplicationContext or a custom context class if specified.  
  4.  * @param servletContext current servlet context  
  5.  * @return the WebApplicationContext implementation class to use  
  6.  * @throws ApplicationContextException if the context class couldn't be loaded  
  7.  * @see #CONTEXT_CLASS_PARAM  
  8.  * @see org.springframework.web.context.support.XmlWebApplicationContext  
  9.  */  
  10. protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException {   
  11.     String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);   
  12.     if (contextClassName != null) {   
  13.         try {   
  14.             return ClassUtils.forName(contextClassName);   
  15.         }   
  16.         catch (ClassNotFoundException ex) {   
  17.             throw new ApplicationContextException(   
  18.                     "Failed to load custom context class [" + contextClassName + "]", ex);   
  19.         }   
  20.     }   
  21.     else {   
  22.         contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());   
  23.         try {   
  24.             return ClassUtils.forName(contextClassName);   
  25.         }   
  26.         catch (ClassNotFoundException ex) {   
  27.             throw new ApplicationContextException(   
  28.                     "Failed to load default context class [" + contextClassName + "]", ex);   
  29.         }   
  30.     }   
  31. }  

Notice: public static final String CONTEXT_CLASS_PARAM = "contextClass";
BeanUtils.java
    
java 代码
  1. public static Object instantiateClass(Constructor ctor, Object[] args) throws BeanInstantiationException {   
  2.        Assert.notNull(ctor, "Constructor must not be null");   
  3.        try {   
  4.            if (!Modifier.isPublic(ctor.getModifiers()) ||   
  5.                    !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {   
  6.                ctor.setAccessible(true);   
  7.            }   
  8.            return ctor.newInstance(args);   
  9.        }   
  10.        catch (InstantiationException ex) {   
  11.            throw new BeanInstantiationException(ctor.getDeclaringClass(),   
  12.                    "Is it an abstract class?", ex);   
  13.        }   
  14.        catch (IllegalAccessException ex) {   
  15.            throw new BeanInstantiationException(ctor.getDeclaringClass(),   
  16.                    "Has the class definition changed? Is the constructor accessible?", ex);   
  17.        }   
  18.        catch (IllegalArgumentException ex) {   
  19.            throw new BeanInstantiationException(ctor.getDeclaringClass(),   
  20.                    "Illegal arguments for constructor", ex);   
  21.        }   
  22.        catch (InvocationTargetException ex) {   
  23.            throw new BeanInstantiationException(ctor.getDeclaringClass(),   
  24.                    "Constructor threw exception", ex.getTargetException());   
  25.        }   
  26.    }   
  27.      
ConfigurableWebApplicationContext.java
java 代码
  1. public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {   
  2.      //context para value分隔符   
  3.     String CONFIG_LOCATION_DELIMITERS = ",; \t\n";   
  4.     void setServletContext(ServletContext servletContext);   
  5.     void setServletConfig(ServletConfig servletConfig);   
  6.     ServletConfig getServletConfig();   
  7.     void setNamespace(String namespace);   
  8.     String getNamespace();   
  9.     void setConfigLocations(String[] configLocations);   
  10.     String[] getConfigLocations();   
  11. }  

In a word, ContextLoaderListener invoke ContextLoader,and ContextLoader delegate and create ConfigurableWebApplicationContext
ConfigurableWebApplicationContext is an object including web servlet context,servletconfig,and contextConfigLocation.
Is is significant as follows

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
context is an object of ConfigurableWebApplicationContext;
分享到:
评论

相关推荐

    .NET CORE open sourse

    .NET CORE open sourse

    wifi module datasheet open sourse

    ### WiFi Module Datasheet Open Source 知识点详解 #### 一、产品概述与特性 **ESP8266WiFi模块**是一款具有超低功耗特性的UART-WiFi透传模块,它以其小巧的封装尺寸和先进的低功耗技术在移动设备及物联网(IoT)...

    OpenSource.zip

    在软件领域,JAR文件(Java归档,英语:Java Archive)是一种软件包文件格式,通常用于聚合大量的Java类文件、相关的元数据和资源(文本、图片等)文件到一个文件,以便开发Java平台应用软件或库。

    DiscordBot-MangoBot-OSV:Discord Bot-Mango Bot-Open Sourse Version

    【标题】"DiscordBot-MangoBot-OSV: Discord Bot-Mango Bot-Open Source Version" 这个项目名为“芒果机器人-OSV”,是基于Python语言实现的一个开源版本的Discord聊天机器人。Discord是一个流行的即时通讯平台,...

    OpenSourseFrame:常用的开源框架的使用和源码分析

    这涉及到对项目需求的理解,例如,如果是Web开发,可能需要考虑Spring Boot、Django或Express.js;如果是移动开发,Android的React Native或Flutter,iOS的SwiftUI可能是选择之一。了解框架的特点、社区支持、性能和...

    Visual SourseSafe 讲义

    ### Visual SourceSafe (VSS) 讲义知识点总结 #### 一、VSS 简介与版本 **1.1 VSS 概述** - **名称解释:** Visual SourceSafe,简称 VSS,是微软公司开发的一款源代码管理工具。 - **功能介绍:** 主要用于软件...

    STM32F103_FOC源代码.rar

    STM32F103系列微控制器是基于ARM Cortex-M3内核的高性能微处理器,由意法半导体(STMicroelectronics)生产。该芯片广泛应用于嵌入式系统设计,特别是工业自动化、电机控制和物联网等领域。FOC,即Field Oriented ...

    sourse insight 破解版

    这是个完全破解的sourse insight 只需按照文件里面介绍一步一步的操作就可以非常顺利的安装 这个sourse insight是属于版本6很好使用

    java SOURSE

    "els_spring"这个文件名可能指的是Spring框架的相关源代码,Spring是Java企业级应用中最流行的一个开源框架,尤其在服务端开发中占据了重要地位。 1. Java基础知识: - 类与对象:Java是一种面向对象的语言,核心...

    离散数学——求集合soursecode

    soursecode离散数学——求集合;soursecode离散数学——求集合;soursecode离散数学——求集合;soursecode离散数学——求集合;soursecode离散数学——求集合;soursecode离散数学——求集合;soursecode

    北大青鸟spring教程(秘密资料冒死上传)

    北大青鸟spring教程(秘密资料冒死上传)

    Sourse Insight 4.0完美破解版

    Source Insight是如今最好用的语言编辑器之一,支持几乎所有的语言, 如C、C++、ASM、PAS、ASP、HTML等常见的,还支持自己定义关键字,Source Insight提供了可快速访问源代码和源信息的功能。

    Android-Open-Sourse-Library:Android 开源组件深度剖析

    Android 开源组件深度剖析 缘起 Android开发中,越来越多优秀的开源组件涌现处出来,可以帮助我们更快更好的实现功能,也节省大量的时间,但是在现实的开发过程中,很多人都没能真正用好开源的组件,我们觉得使用好...

    sql Sourse

    SQL Server 2008是一款广泛使用的数据库管理系统,它提供了高效的数据存储、管理和查询功能。在深入探讨之前,我们先理解几个基本概念。数据库是按照特定数据结构组织、存储和管理数据的仓库,它能够科学地组织数据...

    八数码问题

    - 定义了一些成员函数如:`get_node_value()`、`get_depth()`、`f()`、`get_location(value)`、`show()`、`find_next_node(open[])`、`is_des()`、`is_equal(mm[3][3])` 和 `is_exit(open[])` 等。 2. **全局变量*...

    cms4xml-开源

    cms4xml是使用XML,XSLT,PHP,MDB2,Query2XML,SQL和AJAX的小型,简单且智能的Web内容管理系统。 该cms可以与您的数据库内容或xml输出程序(例如feed(原子))一起简单地2g一起工作。

    SIPPHONE SOURSECODE

    标题"SIPPHONE SOURSECODE"涉及的是一个与SIP(Session Initiation Protocol)电话相关的开源代码项目。SIP是一种用于建立、修改和终止多媒体通信会话的互联网协议,广泛应用于VoIP(Voice over Internet Protocol)...

    StarCraft II: A New Challenge for Reinforcement Learning

    ### 星际争霸II:强化学习的新挑战 #### 摘要与背景 本文介绍了一种基于《星际争霸II》游戏的强化学习环境——SC2LE(StarCraft II Learning Environment)。这一领域为强化学习提出了一个新的重大挑战,相较于...

    pb数据窗口edit sourse说明

    ### PowerBuilder 数据窗口 Edit Source 详解 #### 一、PowerBuilder 概述及 Data Window 编辑源码 PowerBuilder(简称 PB)是一款强大的客户端/服务器应用开发工具,由Sybase公司开发,后被SAP收购。...

Global site tag (gtag.js) - Google Analytics