Spring加载多个配置文件

首先我们都知道要使用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代码  
  
<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"}); 

你可能感兴趣的:(Spring加载多个配置文件)