Spring工具类:WebApplicationContextUtils

当 Web 应用集成 Spring 容器后,代表 Spring 容器的WebApplicationContext对象将以

WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在ServletContext的属性列表中。您当然可以直接通过以下语句获取 WebApplicationContext:

WebApplicationContext wac = (WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

但通过位于 org.springframework.web.context.support 包中的WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:

ApplicationContext ac1 =WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 =WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");

说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

servletContext sc 换成

1.servlet.getServletContext()

2.this.getServletContext() 

3.request.getSession().getServletContext();

实例:

public class demoServlet extends HttpServlet {
 IDemoWS demoWS;
 public void init() throws ServletException {          
        super.init();
        ServletContext servletContext = this.getServletContext();  
        WebApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(servletContext);
        demoWS = (ISignpicWS)ctx.getBean("demoWS");
    }   
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  .....//request.getSession().getServletContext()
 }
}

  

转载于:https://www.cnblogs.com/luoruiyuan/p/5498407.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值