web.xml 通過contextConfigLocation配置spring 的方式
SSI框架配置文件路徑問題:
struts2的 1個+N個 路徑:src+src(可配置) 名稱: struts.xml + N
spring 的 1個 路徑: src 名稱: applicationContext.xml
ibatis 的 1個+N個 路徑: src+src(可配置) 名稱: SqlMapConfig.xml + N
部署到tomcat后,src目錄下的配置文件會和class文件一樣,自動copy到應用的 classes目錄下
spring的 配置文件在啟動時,加載的是web-info目錄下的applicationContext.xml,
運行時使用的是web-info/classes目錄下的applicationContext.xml。
配置web.xml使這2個路徑一致:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
在web.xml中通過contextConfigLocation配置spring,contextConfigLocation 參數定義了要裝入的 Spring 配置文件。
如果想裝入多個配置文件,可以在 <param-value>
標記中用逗號作分隔符。
<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 配置文件。
首先與Spring相關的配置文件必須要以"applicationContext-"開頭,要符合約定優於配置的思想,這樣在效率上和出錯率上都要好很多。
還有最好把所有Spring配置文件都放在一個統一的目錄下,如果項目大了還可以在該目錄下分模塊建目錄。這樣程序看起來不會很亂。
在web.xml中的配置如下:
Xml代碼
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:**/applicationContext-*.xml</param-value>
</context-param>
"**/"表示的是任意目錄;
"**/applicationContext-*.xml"表示任意目錄下的以"applicationContext-"開頭的XML文件。
你自己可以根據需要修改。最好把所有Spring配置文件都放在一個統一的目錄下,如:
<!-- Spring 的配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/applicationContext-*.xml</param-value>
</context-param>
web.xml中classpath:和classpath*:, 有什么區別?
classpath:只會到你的class路徑中查找找文件;
classpath*:不僅包含class路徑,還包括jar文件中(class路徑)進行查找.
在web.xml里配置Listener
xml 代碼如下:
< listener >
<listener-class> org.springframework.web.context.ContextLoaderListener< listener-class>
< /listener>
如果在web.xml里給該Listener指定要加載的xml,如:
xml代碼如下:
<!-- spring config -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
則會去加載相應的xml,而不會去加載/WEB-INF/下的applicationContext.xml。
但是,如果沒有指定的話,默認會去/WEB-INF/下加載applicationContext.xml。