DispatcherServlet以servlet名字加载配置文件并创建spring上下文

本文探讨了一个基于SpringMVC的项目,其中DispatcherServlet在web.xml未明确配置contextConfigLocation的情况下,如何加载名为api-servlet.xml的配置文件。在没有自定义schema或代码加载spring容器的情况下,通过debug发现,当configLocations缺失时,Spring的FrameworkServlet会使用Servlet的名称(如DispatcherServlet)作为namespace加载对应的-servlet.xml配置。这导致ApplicationContext的ID为Servlet名称,并且在ServletContext中以Servlet名称为键存储ApplicationContext。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接手个新项目,基于springMVC的架构。但在web.xml里没有配置DispatcherServlet的初始化参数contextConfigLocation,项目里有个api-servlet.xml的spring配置文件,里面定义的拦截器和bean却都被创建了。以为是项目底层自定义了一些schema或者代码完成了spring容器的加载,但debug后发现并不是。。。

项目web.xml配置如下:

<filter>
  <filter-name>appFilters</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <param-name>contextAttribute</param-name>
    <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.api</param-value>
  </init-param>
  <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
  </init-param>
  <async-supported>true</async-supported>
</filter>
<filter-mapping>
  <filter-name>appFilters</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<servlet>
  <servlet-name>api</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
  <multipart-config>
    <max-file-size>167108864</max-file-size>
    <max-request-size>167108864</max-request-size>
    <file-size-threshold>111204800</file-size-threshold>
  </multipart-config>
</servlet>
<servlet-mapping>
  <servlet-name>api</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

最后开始debug spring容器的加载过程,终于找到了原因。

FrameworkServlet在刷新ApplicationContext时,如果没有configLocations参数时,会使用namespace为前缀的xml进行容器加载。namespace如果没有指定,则使用DispatcherServlet的名字+“-servlet”作为namespace名字。同时以DispatcherServlet的名字作为ApplicationContext的ID:id = "org.springframework.web.context.WebApplicationContext:/api"

上下文初始化完成后,会将ApplicationContext放入ServletContext,以DispatcherServlet的名字。

if (this.publishContext) {
   // Publish the context as a servlet context attribute.
   String attrName = getServletContextAttributeName();
   getServletContext().setAttribute(attrName, wac);
}

attrName = "org.springframework.web.servlet.FrameworkServlet.CONTEXT.api"

所以DelegatingFilterProxy指定了参数contextAttribute,使用api为id的上下文,使用默认root的上下文是null。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值