开发Java Web程序,使用ssh架构时,默认情况下,Spring的配置文件applicationContext.xml存放在
项目下的“web-inf/applicationContext.xml”目录下,默认时,Spring会加载这个文件,完成Spring的配置。
如果想改变配置文件的名称,或者想添加多个Spring的配置文件,则可以通过如下方式添加。
在web.xml文件中添加如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/config/spring-config/applicationContext-*.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
< 省略其他配置...>
</web-app>
上面使用的是通配符:applicationContext-*.xml 来添加多个匹配的Spring配置文件,这样添加完成后,
Spring就不会去加载“web-inf/applicationContext.xml”这个默认的文件了,而是去加载下面这个路径下
的Spring配置文件:
/WEB-INF/classes/config/spring-config/applicationContext-*.xml;
也可以使用如下方式添加多个Spring配置文件:
<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>
-
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
配置文件之间通过“,”逗号隔开;
说明:
上面两种方式有以下注意点:
1. <param-name>contextConfigLocation</param-name> 中,<param-name>的值必须为:contextConfigLocation;
因为配置的监听器<listener>会默认通过contextConfigLocation的值来寻找配置文件的位置;
2. 必须要配置<listener> ,使用org.springframework.web.context.ContextLoaderListener 即可;