Spring配置文件詳解 – applicationContext.xml文件路徑
spring的配置文件applicationContext.xml的默認地址在WEB-INF下,只要在web.xml中加入代碼
1
2
3
4
5
|
< listener >
< listener-class >
org.springframework.web.context.ContextLoaderListener
</ listener-class >
</ listener >
|
spring就會被自動加載
但在實際的開發過程中,我們可能需要調整applicationContext.xml的位置,以使程序結構更加的清晰。在web.xml中,配置Spring配置文件的代碼如下:
1
2
3
4
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >這里寫路勁</ param-value >
</ context-param >
|
根據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會默認去加載,如果一定要配置呢,可以這樣
1
2
3
4
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >WEB-INF/applicationContext.xml</ param-value >
</ context-param >
|
2、Spring配置文件在WEB-INF下的某個文件夾下,比如config下,可以這樣配置
1
2
3
4
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >WEB-INF/config/applicationContext.xml</ param-value >
</ context-param >
|
3、Spring配置文件在src下面,可以這樣配置
1
2
3
4
|
< init-param >
< param-name >contextConfigLocation</ param-name >
< param-value >classpath:applicationContext.xml</ param-value >
</ -param >
|
或者
1
2
3
4
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >classpath:applicationContext.xml</ param-value >
</ context-param >
|
4、Spring配置文件在src下的某個包里,比如com.config,可以這樣配置
1
2
3
4
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >WEB-INF/classes/com/config/applicationContext.xml</ param-value >
</ context-param >
|
或者
1
2
3
4
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >classpath:com/config/applicationContext.xml</ param-value >
</ context-param >
|