在web应用中创建spring容器有以下两种方式:
1) 直接在web.xml文件中配置spring容器
2)利用MVC框架扩展点,创建spring容器
一、直接在web.xml文件中配置spring容器
ServletContextListener监听器可以在web应用启动时回调自定义方法——该方法就可以启动spring容器。
Spring提供了一个ContextLoaderListener,改监听器实现了ServletContextListener接口。该类可以作为Listener使用,它会在创建时自动查询WEB-INF/下的applicationContext.xml,因此,如果只有一个配置文件,并且文件名为applicationContext.xml,则只需在web.xml中增加人如下配置片段即可:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果有多个配置文件需要加载,则考虑使用<context-pararm.../>元素来确定文件的文件名,ContextLoaderListener加载时,会查找名为contextConfigLocation的初始化参数,因此,配置<context-pararm.../>时应指定参数名为contextConfigLocation。
带多个配置文件的web.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 多个配置文件中间用逗号分隔 -->
<param-value>/WEB-INF/config/web-application-config.xml
,/WEB-INF/config/daoContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Spring根据指定的配置文件创建WebApplicationContext对象,并将其保存在web应用的ServletContext中,如果需要在应用中获取ApplicaitonContext对象,则通过以下代码获取:
//获取当前web应用启动的spring容器
WebApplicationContext ctx
= WebApplicationContextUtils.getWebApplicationContext(servletContext);