介绍Spring容器时,已经清楚地说过,对于使用Spring的Web应用,无须手动创建Spring容器,而是通过配置文件,声明式地创建Spring容器。因此在Web应用中创建Spring容器有如下两种方式:
- 直接在web.xml文件中配置创建Spring容器。
- 利用第三方MVC框架的扩展点,创建Spring容器。
其实第一种创建Spring窗口的方式更加常见。为了让Spring容器随Web应用的启动而自动启动,借助于ServletContextListener监听器即可完成,该监听器可以在Web应用启动时回调自定义方法——该方法就可以启动Spring容器。
Spring 提供了一个ContextLoadListener,该监听器类实现了ServletContextListener接口。该类可以作为Listener使用,它会在创建时自动查找 WEB-INF/ 下的 applicationContext.xml 文件,因此,如果只有一个配置文件,并且文件名为 applicationContext.xml,则只需在 web.xml 文件中增加如下配置片段即可。
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
如果有多个配置文件需要载入,则考虑使用 <context-param.../> 元素来确定配置文件的文件名。ContextLoaderListener 加载时,会查找名为 contextConfigLocation 的初始化参数。因此,配置 <context-param.../> 时应指定参数名为 contextConfigLocation。
带多个配置文件的 web.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!--指定多个配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml,/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
如果没有使用 contextConfigLocation 指定配置文件,则 Spring 自动查找 applicationContext.xml 配置文件:如果有 contextConfigLocation,则利用该参数确定的配置文件。如果无法找到合适的配置文件,Spring 将无法正常初始化。
Spring 根据指定配置文件创建 WebApplicationContext 对象,并将其保存在 Web 应用的 ServletContext 中。大部分情况下,应用中的 Bean 无须感受到 ApplicationContext的存在,只要利用ApplicationContext 的 IoC 即可.
如果需要在应用中获取 ApplicationContext 实例,则可以通过如下代码获取:
//获取当前Web应用的Spring容器 WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
当然,也可以通过 ServletContext 的 getAttribute 方法获取 ApplicationContext。但使用 WebApplicationContextUtils 类更方便,因为这样无须记住 ApplicationContext 在 ServletContext 中的属性名(属性名为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)。使用 WebApplicationContextUtils 还有一个额外的好处:即使 ServletContext 的 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 属性没有相应的对象,WebApplicationContextUtils 的 getWebApplicationContext() 方法将会返回空,而不会引起异常。
还有一种情况,即利用第三方MVC框架的扩展点来创建 Spring 容器,比如 Struts1,但这种情况通常只对特定框架才有效,故此处不再赘述。