web容器加载Spring配置文件

首先我们都知道要在web项目中通过容器自动加载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>  

另外还这样这样走,在applicationContext.xrnl 文件中加入自定义的多个配置文件,如下所示:

Xml代码 
<beans> 
    <import resource="classpath:applicationContext-db.xml" /> 
    <import resource="classpath:applicationContext-order.xml" /> 
    <import resource="classpath:applicationContext-product.xml" /> 
    <import resource="classpath:applicationContext-pay.xml" /> 
    <import resource="classpath:applicationContext-activity.xml" /> 
    <import resource="classpath:applicationContext-logo.xml" /> 
    <import resource="classpath:applicationContext-paycar.xml" /> 
</beans> 
这样的话,只需在web.xml中引入配置文件 applicationContext.xrnl 即可。


多个配置文件用","分开,也可以使用通配符"*"加载多个配置文件。如上例!
   如果是直接在java代码中加载多个配置文件该怎么做呢?请看下面实例:
Java代码
ApplicationContext context= new ClassPathXmlApplicationContext(new String[]{"bean1.xml","bean2.xml"}); 

猜你喜欢

转载自yimengdaotianming.iteye.com/blog/1194714