在Web应用程序中,ApplicationContext是在web.xml文件中配置的。如果Servlet容器支持Servlet2.3规范,就可以使用org.springframework.web.context.ContextLoaderListener,如代码:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
ContextLoaderListener不能与某些Servlet2.3容器兼容。如果你使用的是这种Servlet容器,就需要在web.xml文件中配置org.springframework.web.context.ContextLoaderServlet Servlet,而不是ContextLoaderListener。ContextLoaderListener不能正确地与下面这些Servlet2.3容器一起工作。
- BEA Weblogic 8.1 SP2和更早的版本
- IBM WebSphere 6.0之前的版本
- Oracle OC4J 10g之前的版本
如果使用Servlet2.2容器,还必须使用ContextLoaderServlet,代码如下:
在web.xml中配置ContextLoaderServlet
<servlet>
<servlet-name>contextLoaderServlet</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
由ContextLoaderListener和ContextLoaderServlet创建的ApplicationContext被放在Web应用程序的ServletContext对象中。如果提供ServletContext对象,org.springframework.web.context.support.WebApplicationContextUtils类就将返回ApplicationContext对象,像下面这样:
ApplicationContext applicationContext =
WebApplicationContextUtils.getWebApplicationContext(servletContext);
默认情况下,ContextLoaderListener和ContextLoaderServlet加载/WEB-INF/applicationContext.xml文件。这个位置可以通过在web.xml中定义contextConfigLocation上下文参数进行覆盖,代码如下:
通过contextConfigLocation参数指定XML文件位置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:service-context.xml <!--这里是你的配置文件-->
classpath:data-access-context.xml
</param-value>
</context-param>
由ContextLoaderListener和ContextLoaderServlet为应用程序上下文加载的默认资源位置是web应用程序的ServletContext对象。
以上配置好后,你就可以在你的Action当中利用ServletActionContext.getServletContext()来获取ServletContext对象。