天天看點

Spring配置檔案詳解 - applicationContext.xml檔案路徑

  spring的配置檔案applicationContext.xml的預設位址在WEB-INF下,隻要在web.xml中加入代碼

org.springframework.web.context.ContextLoaderListener      

    spring就會被自動加載

    但在實際的開發過程中,我們可能需要調整applicationContext.xml的位置,以使程式結構更加的清晰。在web.xml中,配置Spring配置檔案的代碼如下:

contextConfigLocation這裡寫路勁      

    根據Spring架構的API描述,有以下四種方法配置applicationContext.xml檔案路徑

1. /WEB-INF/applicationContext.xml
2. com/config/applicationContext.xml
3. file:C:/javacode/springdemo/com/config/applicationContext.xml
4. classpath:com/config/applicationContext.xml      

注:以上路徑隻是舉例,具體使用還是要針對真是項目的,做程式設計的這點舉一反三能力還是有的吧

    開發過程中,如果spring的配置檔案applicationContext.xml未加載的話,一般回報這樣的錯誤 Could not open ServletContext resource [/WEB-INF/applicationContext.xml] 下面就有我為大家舉例自定義applicationContext.xml路徑的常見的方法。

    1、Spring配置檔案在WEB-INF下面

Spring配置檔案詳解 - applicationContext.xml檔案路徑

    這種情況你可以不去管他,不進行配置,因為spring會預設去加載,如果一定要配置呢,可以這樣

contextConfigLocationWEB-INF/applicationContext.xml      

    2、Spring配置檔案在WEB-INF下的某個檔案夾下,比如config下,可以這樣配置

Spring配置檔案詳解 - applicationContext.xml檔案路徑
contextConfigLocationWEB-INF/config/applicationContext.xml      

    3、Spring配置檔案在src下面,可以這樣配置

Spring配置檔案詳解 - applicationContext.xml檔案路徑
contextConfigLocationWEB-INF/classes/applicationContext.xml      

或者

contextConfigLocationclasspath:applicationContext.xml      

    4、Spring配置檔案在src下的某個包裡,比如com.config,可以這樣配置

Spring配置檔案詳解 - applicationContext.xml檔案路徑
contextConfigLocationWEB-INF/classes/com/config/applicationContext.xml      

或者

contextConfigLocationclasspath:com/config/applicationContext.xml