资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Spring使用多个xml配置文件的方法-创新互联

这篇文章给大家分享的是有关Spring使用多个xml配置文件的方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

成都创新互联公司成立与2013年,是专业互联网技术服务公司,拥有项目成都网站设计、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元永吉做网站,已为上家服务,为永吉各地企业和个人服务,联系电话:13518219792

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

contextConfigLocation
classpath*:conf/spring/applicationContext_core*.xml,
classpath*:conf/spring/applicationContext_dict*.xml,classpath*:conf/spring/applicationContext_hibernate.xml,
classpath*:conf/spring/applicationContext_staff*.xml,classpath*:conf/spring/applicationContext_security.xml
classpath*:conf/spring/applicationContext_modules*.xmlclasspath*:conf/spring/applicationContext_cti*.xml
classpath*:conf/spring/applicationContext_apm*.xml

contextConfigLocation 参数定义了要装入的 Spring 配置文件。原理说明如下:

1.利用ServletContextListener 实现。
Spring 提供ServletContextListener 的一个实现类ContextLoaderListener ,该类可以作

为listener 使用,它会在创建时自动查找WEB-INF/ 下的applicationContext.xrnl 文件。因
此,如果只有一个配置文件,并且文件名为applicationContext.xml ,则只需在web.xml

文件中增加如下代码即可:


org.springframework.web.context.ContextLoaderListener

如果有多个配置文件需要载入,则考虑使用文件名。由于ContextLoaderListener加载时,会查找名为contextConfigLocation的参数。

因此,配置context-param时参数名字应该是contextConfigLocation。
带多个配置文件的web.xml 文件如下:

<1-- XML 文件的文件头二〉
< 1-- web.xm1 文件的DTD 等信息一〉

<1-- 参数名为contextConfigLocation…〉
contextConfigLocation/WEB-工NF/daoContext.xml./WEB-INF/applicationContext.xml

org.spr工ngframework.web.context.ContextLoader
Listener

如果没有contextConfigLocation 指定配置文件,则Spring 自动查找application
Context. xrnl 配置文件。如果有contextConfigLocation,则利用该参数确定的配置文件。

该参数指定的一个字符串, Spring 的ContextLoaderListener 负责将该字符串分解成多个
配置文件,逗号","、空格" "及分号";"都可作为字符串的分割符。

如果既没有applicationContext. xrnl 文件,也没有使用contextConfigLocation参数确
定配置文件,或者contextConfigLocation确定的配置文件不存在。都将导致Spring 无法

加载配置文件或无法正常创建ApplicationContext 实例
配置一个spring为加载而设置的servlet可以达到同样效果.

采用load-on-startup Servlet 实现。
Spring 提供了一个特殊的Servllet 类: ContextLoaderServlet。该Servlet 在启动时,会

自动查找WEB-IN日下的applicationContext. xml 文件。
当然,为了让ContextLoaderServlet 随应用启动而启动,应将此Servlet 配置成

load-on-startup 的Servleto load-on-startup 的值小一点比较合适,因为要保证Application
Context 优先创建。如果只有一个配置文件,并且文件名为applicationContext. xml ,则在

web.xml 文件中增加如下代码即可:


contextorg.springframework.web.context.ContextLoaderServletl

。带多个配置文件的web且nl 文件如下:



<'一确定多个配置文件一>
contextConfigLocation