1, 在web.xml中定義 contextConfigLocation參數.spring會使用這個參數加載.所有逗號分割的xml.如果沒有這個參數,spring默認加載web-inf/applicationContext.xml文件
<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, classpath*:conf/spring/applicationContext_staff*.xml, classpath*:conf/spring/applicationContext_security.xml classpath*:conf/spring/applicationContext_modules*.xml classpath*:conf/spring/applicationContext_cti*.xml classpath*:conf/spring/applicationContext_apm*.xml </param-value> </context-param>
contextConfigLocation 參數定義了要裝入的 Spring 配置文件。原理說明如下:
、利用ServletContextListener 實現。
Spring 提供ServletContextListener 的一個實現類ContextLoaderListener ,該類可以作
為listener 使用,它會在創建時自動查找WEB-INF/ 下的applicationContext.xrnl 文件。因
此,如果只有一個配置文件,並且文件名為applicationContext.xml ,則只需在web.xml
文件中增加如下代碼即可:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
如果有多個配置文件需要載入,則考慮使用<context-para即元素來確定配置文件的
文件名。由於ContextLoaderListener加載時,會查找名為contextConfigLocation的參數。
因此,配置context-param時參數名字應該是contextConfigLocation。
帶多個配置文件的web.xml 文件如下
<!-- XML 文件的文件頭--〉 <?xml version="l.O" encoding="工80-8859-1"?> <!-- web.xm1 文件的DTD 等信息--〉 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems. 工口c.//DTD Web Application 2.3//EN" ''http://java.sun.com/dtd/web-app_2_3.dtd''> <web-app> <!--確定多個配置文件--> <context-param> <!-- 參數名為contextConfigLocation…--〉 <param-name>contextConfigLocation</param-name> <!一多個配置文件之間以,隔開--〉 <param-value> /WEB-INF/daoContext.xml, /WEB-INF/applicationContext.xml</param-value> </context-param> <!-- 采用listener創建Applicat工onContext 實例--> <listener> <listener-class>org.spr工ngframework.web.context.ContextLoader Listener</listener-class> </listener> </web-app>