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下面

配置文件在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下,可以这样配置
配置文件在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下面,可以这样配置
配置文件在src根目录下

1
2
3
4
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >WEB-INF/classes/applicationContext.xml</ param-value >
</ context-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,可以这样配置
配置文件在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 >