WebApplicationContext的初始化方式和BeanFactory.ApplicationContext有所区别,因为WebApplicationContext需要ServletContext实例,也就是说它必须拥有Web容器的前提下才能完成启动的工作.有过Web开发经验的读者都知道可以在web.xml中配置自启动的Servlet或定义Web容器监听器(ServletContextListener),借助着两者中的任何一个,我们就可以启动Spring Web应用上下文的工作.
Spring分别提供了用于启动WebApplicationContext的Servlet和Web容器监听器:
org.springframework.web.context.ContextLoaderServlet;
org.springframework.web.context.ContextLoaderListener.
两者的内部都实现了启动WebApplicationContext实例的逻辑,我们只要根据Web容器的具体情况选择两者之一,并在web.xml中完成配置就可以了.
下面是使用ContextLoaderListener启动WebApplicationContext 的具体配置:
通过Web容器监听器引导
......
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/lxm-dao.xml,/WEB-INF/lxm-servicer.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener通过Web容器上下文参数contextConfigLocation获取Spring配置文件的位置.用户可以指定多个配置文件,用逗号.空格或冒号分割均可.配置文件路径Web应用路径跟目录的方式进行指定.
如果在支持低版本Servlet的Web容器中,可采用ContextLoaderServlet完成相同的工作:
.....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/lxm-dao.xml,/WEB-INF/lxm-service.xml</parm-value>
</context-param>
.......
<servlet>
<servlet-name>springContextLoaderServlet</servlet-name>
<servlet-class>org.springframework.context.ContextLoadrServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
由于WebAppplicationContext需要使用日志功能,用户可以将Log4J的配置文件放置到类路径WEB-INF/classes下,这时Log4J引擎将可以顺序启动.如果Log4J配置文件放置在其他位置,用户还必须在web.xml指定Log4J配置文件位置.Spring为启用Log4J引擎提供了两个类似于启用WebApplicationContext的实现类:Log4jContextServlet和Log4jContextListener,不管采用那种方式都必须保证能够在装载Spring配置文件前装载Log4J配置信息.
指定Log4J配置文件时启动Spring Web应用上下文
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/lxm-dao.xml,/WEB-INF/lxm-service.xml
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<servlet>
<servlet-name>log4jConfigServlet</servlet-name>
<servlet-class>org.springframework.web.util.Log4jConfigServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>springContextLoaderServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>