【转】web.xml中的contextConfigLocation在spring中的作用

一、spring中如何使用多个xml配置文件

  1、在web.xml中定义contextConfigLocation参数,Spring会使用这个参数去加载所有逗号分隔的xml文件,如果没有这个参数,spring会默认加载WEB-INF/applicationContext.xml文件(若没有,要新建一个)。

  例如:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:conf/spring/applicationContext_core*.xml,
        classpath*:conf/spring/applicationContext_dict*.xml,
        classpath*:conf/spring/applicationContext_hibernate.xml,
    </param-value>
</context-param>

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

  PS:classpath指编译后的class路径。包含 WEB-INF/lib下的所有jar包和WEB-INF/classes目录

  原理:利用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。

  带多个配置文件的web.xml文件如下:

<web-app>
  <!--确定多个配置文件-->
  <context-param>
    <!-- 参数名为contextConfigLocation…-->
    <param-name>contextConfigLocation</param-name>
    <!--多个配置文件之间以,隔开-->
    <param-value>/WEB-工NF/daoContext.xml./WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <!-- 采用listener创建ApplicationContext 实例-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

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

二、使用通配符

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

  比如说用到Hibernate,则把hibernate相关的配置放在applicationContext-hibernate.xml这一个文件,而一些全局相关的信息则放在applicationContext.xml中,其它的配置文件类似,这样就不必用空格或逗号分开多个配置文件了。

猜你喜欢

转载自www.cnblogs.com/codingmengmeng/p/10770587.html
今日推荐