当柳上原的风吹向天际的时候...

真正的快乐来源于创造

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  368 Posts :: 1 Stories :: 201 Comments :: 0 Trackbacks

在WebApp中获得XMLWebApplicationContext的步骤
1.在Web.xml中配置上下文载入器.
2.指定上下文载入器的配置文件.
3.获得应用上下文.

1.在Web.xml中配置上下文载入器
根据你的系统情况,你可以选择两种上下文载入器:ContextLoaderListener和ContextLoaderServlet.如果你的Web容器支持Servlet2.3标准或更高,你可以使用两者,否则只能使用后者.
ContextLoaderListener在Web.xml应该如下配置:

<listener> 
     
<listener-class>
          org.springframework.web.context.ContextLoaderListener
     
</listener-class> 
</listener> 

ContextLoaderServlet在Web.xml应该如下配置:

<servlet>
  
<servlet-name>context</servlet-name>
  
<servlet-class>
  org.springframework.web.context.ContextLoaderServlet
  
</servlet-class>
  
<load-on-startup>1</load-on-startup>
</servlet>


2.指定上下文载入器的配置文件

不论你使用的那种上下文载入器,你都应该指明Spring配置文件的位置.如果没有指定,上下文载入器将把/web-inf/application-Context.xml当作Spring配置文件。
要指定Spring配置文件的位置,你可以在Servlet上下文设置contextConfigLocation参数来为上下文载入器指定一个或多个Spring配置文件(使用通配符或是用逗号隔开)。如下所示:

<context-param>
    
<param-name>
         contextConfigLocation
   
</param-name>
   
<param-value>
          /WEB-INF/cfg/bean.xml
   
</param-value>
</context-param>

 

3.获得应用上下文
接下来我们就可以获得ApplicationContext了,代码如下:

WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); 

在一个自启动的Servlet中,我们可以这样获得它:

public class InitialSystemServlet extends HttpServlet {
  
public void init(ServletConfig config) throws ServletException {
    
// 取得Spring的上下文
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
    ..
  }

  
  ..
}

如果把获得的上下文的地址给一个静态引用,我们以后就可以在应用中的任意位置使用ApplicationContext了。

posted on 2008-11-24 23:19 何杨 阅读(8619) 评论(1)  编辑  收藏

Feedback

# re: Spring在Web应用中的配置[未登录] 2013-08-22 22:40 ddd
dfdffddf  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: