web.xml中如何設置配置文件的加載路徑


 web應用程序通過Tomcat等容器啟動時,會首先加載web.xml文件,通常我們工程中的各種配置文件,如日志、數據庫spring的文件等都在此時被加載,下面是兩種常用的配置文件加載路徑,即配置文件可以放到 SRC目錄下或者可以放到WEB-INF根目錄下

 

第一種在web.xml中這樣配置:
   <context-param>
     <param-name >contextConfigLocation </param-name >
     <param-value >classpath:config/XXXXXXX.xml </param-value >
 </ context-param>
  表示在類路徑下有一個名為config的文件夾
第二種在web.xml中這樣配置:
<context-param>
     <param-name >contextConfigLocation </param-name >
     <param-value >/WEB-INF/config/*-context.xml </param-value >
 </ context-param>
放在config文件夾下,使用了通配符。兩種方式功能一樣,使用哪個就看個人喜好了。
 
 
 
、、、、、、、、、、、、、、、、、、、、

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>

多個配置文件的加載

[html]  view plain  copy
 
  1. <context-param>  
  2.         <param-name>contextConfigLocation</param-name>  
  3.         <param-value>  
  4.             classpath*:conf/spring/applicationContext_core*.xml,  
  5.             classpath*:conf/spring/applicationContext_dict*.xml,  
  6.             classpath*:conf/spring/applicationContext_hibernate.xml,  
  7.             classpath*:conf/spring/applicationContext_staff*.xml,  
  8.             classpath*:conf/spring/applicationContext_security.xml  
  9.             classpath*:conf/spring/applicationContext_modules*.xml  
  10.             classpath*:conf/spring/applicationContext_cti*.xml  
  11.             classpath*:conf/spring/applicationContext_apm*.xml  
  12.         </param-value>  
  13.     </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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM