欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring加载多个配置文件 博客分类: 框架 xmlcontextspringlistenerspringframework

程序员文章站 2024-02-24 21:25:58
...
首先我们都知道要使用spring,则需要在web.xml中增加如下代码:

Xml代码  
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>     spring是如何加载配置文件肯定也跟 ContextLoaderListener类有关,该类可以作为listener 使用,它会在创建时自动查找WEB-INF/ 下的applicationContext.xrnl 文件。因此,如果只有一个配置文件,并且文件名为applicationContext.xml ,则只需在web.xml加上面代码即可。



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

  比如下面的示例:



Xml代码 
1. <context-param> 
2.<param-name>contextConfigLocation</param-name> 
3.<param-value> 
4.classpath*:conf/spring/applicationContext*.xml,  
5.classpath*:conf/spring/applicationContext_dict*.xml,  
6.</param-value> 
7.</context-param>  
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:conf/spring/applicationContext*.xml,
classpath*:conf/spring/applicationContext_dict*.xml,
</param-value>
</context-param> 
多个配置文件用","分开,也可以使用通配符"*"加载多个配置文件。如上例!

   如果是直接在java代码中加载多个配置文件该怎么做呢?请看下面实例:

Java代码 
1.ApplicationContext context= new ClassPathXmlApplicationContext(new String[]{"bean1.xml","bean2.xml"});