在WebApp中获得XMLWebApplicationContext的步骤1.在Web.xml中配置上下文载入器.
2.指定上下文载入器的配置文件.
3.获得应用上下文.
1.在Web.xml中配置上下文载入器根据你的系统情况,你可以选择两种上下文载入器:ContextLoaderListener和ContextLoaderServlet.如果你的Web容器支持Servlet2.3标准或更高,你可以使用两者,否则只能使用后者.
ContextLoaderListener在Web.xml应该如下配置:
org.springframework.web.context.ContextLoaderListener
ContextLoaderServlet在Web.xml应该如下配置:
context
org.springframework.web.context.ContextLoaderServlet
1
2.指定上下文载入器的配置文件
不论你使用的那种上下文载入器,你都应该指明Spring配置文件的位置.如果没有指定,上下文载入器将把/web-inf/application-Context.xml当作Spring配置文件。
要指定Spring配置文件的位置,你可以在Servlet上下文设置contextConfigLocation参数来为上下文载入器指定一个或多个Spring配置文件(使用通配符或是用逗号隔开)。如下所示:
contextConfigLocation
/WEB-INF/cfg/bean.xml
3.获得应用上下文
接下来我们就可以获得ApplicationContext了,代码如下:
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(servletContext);
在一个自启动的Servlet中,我们可以这样获得它:
publicclassInitialSystemServletextendsHttpServlet
{
publicvoidinit(ServletConfig config)throwsServletException
{
//取得Spring的上下文
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
..
}
..
}
如果把获得的上下文的地址给一个静态引用,我们以后就可以在应用中的任意位置使用ApplicationContext了。