您的位置:首页 > 编程语言 > Java开发

Spring在Web应用中的配置

2013-07-25 20:21 302 查看
在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了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: