WebApplicationContext继承自ApplicationContext,是专门为Web应用准备的BeanFactory(支持Web特性),它允许从相对于Web根目录的路径中装载配置文件,完成初始化工作。从WebApplicationContext中可以获得ServletContext的引用,整个Web应用上下文对象将作为属性放在ServletContext中,以便Web应用环境可以访问Spring应用上下文。
1. WebApplicationContext的初始化
WebApplicationContext的初始化方式和BeanFactory、ApplicationContext的初始化方式有所区别,因为WebApplicationContext需要ServletContext实例,也就是说它必须在拥有Web容器的前提下才能完成启动的工作。Spring分别提供了用于启动WebApplicationContext的Servlet和Web容器监听器(Listener)。
org.springframework.web.context.ContextLoaderServlet
org.springframework.web.context.ContextLoaderListener
两者的内部都实现了启动WebApplicationContext实例的逻辑,用户只需要根据Web容器的情况 选择两者之一,并在web.xml中完成配置就可以了。
web.xml配置如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- or use the ContextLoaderServlet instead of the above listener
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->
ContextLoaderListener通过Web容器上下文参数contextConfigLocation获取Spring配置文件的位置。用户可以指定多个配置文件,用逗号、空格、分号分隔均可(建议使用逗号进行分隔)。对于未做资源类型前缀的配置文件路径,WebApplicationContext默认这些路径是相对于Web的部署根路径。当然,可以采用带资源类型的路径配置,如“calsspath:/applicationContext.xml”、“classpath*:applicationContext*.xml”。
在不支持容器监听器的低版本Web容器中,可采用ContextLoaderServlet来完成相同的工作。