前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringMVC源码阅读:ContextLoaderListener初始化过程

SpringMVC源码阅读:ContextLoaderListener初始化过程

作者头像
飞狗
发布2018-12-14 14:44:10
7230
发布2018-12-14 14:44:10
举报

概述

  • Tomcat或Jetty作为Servlet容器会为每一个Web应用构建一个ServletContext用于存放所有的Servlet, Filter, Listener。
  • ContextLoaderListener 作为一个Listener会首先启动,创建一个WebApplicationContext用于加载除Controller等Web组件以外的所有bean,这个ApplicationContext作为根容器存在,对于整个Web应用来说,只能存在一个,也就是父容器,会被所有子容器共享,子容器可以访问父容器里的bean,反过来则不行。

web.xml配置

ContextLoaderListener监听器的作用就是启动web容器时,自动装配ApplicationContext的配置信息。它实现了ServletContextListener接口,在web.xml文件中配置这个监听器,Tomcat或Jetty启动容器时,就会默认执行它实现的方法。

代码语言:javascript
复制
<!-- 配置spring IOC参数路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-context*.xml</param-value>
    </context-param> 
<!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-    
         class>
    </listener>

通过扩展ContextLoaderListener类,可以增加初始化时的个性化功能,如输出产品的信息等。

获取WebApplicationContext的实现类

在org.springframework.web.context.ContextLoader中有一个静态属性,

代码语言:javascript
复制
static {
        // Load default strategy implementations from properties file.
        // This is currently strictly internal and not meant to be customized
        // by application developers.
        try {
            ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
        }
    }

默认的DEFAULT_STRATEGIES_PATH=ContextLoader.properties,路径在ContextLoader类的同一级目录下,都在spring-web-..*.RELEASE.jar包内。ContextLoader.properties的内容为:

代码语言:javascript
复制
# 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

实际的实例化为org.springframework.web.context.support.XmlWebApplicationContext。

知识点

  • org.springframework.core.ioClassPathResource和PropertiesLoaderUtils.loadProperties()组合读取jar包中的properties配置文件。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.11.19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • web.xml配置
  • 获取WebApplicationContext的实现类
  • 知识点
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档