在web工程里面使用spring时,需要在web.xml里面配置相关的spring的上下文配置的路径(contextConfigLocation),通常有以下几种配置

 



<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext.xml
</param-value>
</context-param>


 

 



<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/applicationContext.xml
</param-value>
</context-param>


一:classpath:只会从当前工程的class路径下查找文件;classpath*:不光是当前工程的class路径,还包括所引用的jar中的class路径。

二:如果将文件放在了src的类相关的路径下,也可以进行如下配置(web工程的类路径下的东西最终在服务器运行的时候都需要放到/WEB-INF/classes/目录下)



<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext.xml
</param-value>
</context-param>


三:不放在src的类相关的路径下,可以直接放在web工程的WEB-INF目录下,则相关的web.xml配置如下:



<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>


四:spring的上下文配置的举例

/WEB-INF/**/*Context.xml:/WEB-INF/**/表示WEB-INF下的任何路径,*Context.xml表示任何以Context.xml结尾的文件

不使用“*”号通配符时,多个配置文件可以以空格或逗号或分号隔开来加以区分。

:web工程在启动时需要先初始化上下文环境

在web.xml配置ContextLoaderListener



<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


或者设置ContextLoaderServlet的load-on-start

 



<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>