web.xml中的contextConfigLocation在Spring中的作用

在web.xml中定义contextConfigLocation参数,Spring会使用这个参数去加载所有逗号分隔的xml文件,如果没有这个参数,Spring默认加载web-inf/applicationContext.xml文件。

例如

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
		classpath*:applicationContext.xml,
		classpath*:spring-security.xml
    </param-value>
</context-param> 

contextConfigLocation 参数的<param-value>定义了要装入的 Spring 配置文件。

原理:利用ServletContextListener 实现

Spring 提供ServletContextListener 的一个实现类ContextLoaderListener ,该类可以作为 listener监听器使用,它会在创建时自动查找WEB-INF/ 下的applicationContext.xml 文件。因此,如果只有一个配置文件,并且文件名为applicationContext.xml ,则只需在web.xml文件中增加如下代码即可:

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

如果有多个配置文件需要载入,则考虑使用<context-param>元素来确定配置文件的文件名。由于ContextLoaderListener加载时,会查找名为contextConfigLocation的参数。因此,配置<context-param>时参数名字应该是contextConfigLocation。

如果没有 contextConfigLocation 指定配置文件,则Spring 自动查找applicationContext.xml 配置文件。如果有 contextConfigLocation,则利用该参数确定的配置文件。该参数指定的一个字符串,Spring 的ContextLoaderListener 负责将该字符串分解成多个配置文件,逗号","、空格" “及分号”;"都可作为字符串的分割符。如果既没有 applicationContext.xml 文件,也没有使用contextConfigLocation参数确定配置文件,或者contextConfigLocation确定的配置文件不存在。都将导致Spring 无法加载配置文件或无法正常创建ApplicationContext 实例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值