Insight Spring MVC 配置加载机制

本文介绍了Spring MVC中DispatcherServlet的两种配置方法:通过设置contextConfigLocation指定配置文件路径和使用默认约定路径加载配置文件。详细解释了setConfigLocation方法支持的多路径配置方式,并展示了如何在web.xml中进行具体配置。

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

DispatcherServlet配置两种方式:

  • 指定配置文件路径,set contextConfigLocation
  • 配置文件使用约定的路径和命名方式
<!--声明指定配置文件路径,servlet.init()过程会转换ServletConfig,作为DispatcherServlet 初始化参数,完成contextConfigLocation的set操作-->
<servlet>
    <servlet-name>sample</servlet-name>
    <servlet-class>org.s.w.s.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:conf/sample-servlet.xml
        </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

<!--加载约定(默认)路径/WEB-INF/{servlet-name}-servlet.xml-->
<servlet>
    <servlet-name>sample</servlet-name>
    <servlet-class>org.s.w.s.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

Insight 清单:

  • setConfigLocation支持多种符号分隔的多路径配置
// with distinct locations separated by commas, semicolons or whitespace.
// see org.springframework.web.servlet.FrameworkServlet
public void setConfigLocation(String location) {
    setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}
  • 如果没有声明指定configLocations,会尝试加载约定(默认)的配置
protected String[] getConfigLocations() {
    return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
}
  • 约定路径即:/WEB-INF/ + getNamespace() + .xml
  • Spring core对于资源抽象为Resource接口,约定的配置文件体现为ServletContextResource
  • 约定的配置文件操作,委托给servletContext实现
public InputStream getInputStream() throws IOException {
    InputStream is = this.servletContext.getResourceAsStream(this.path);
    if (is == null) {
        throw new FileNotFoundException("Could not open " + getDescription());
    }
    return is;
}
  • 特别说明,Insight源码,注意基类的实现以及真正实现类的override ,否则很容易迷路、困惑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值