spring在web应用中的配置

Spring在Web应用中的配置

在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了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值