zoukankan      html  css  js  c++  java
  • Spring工具类:WebApplicationContextUtils

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

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

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

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

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

    1
    2
    3
    4
    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();

    实例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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()
     }
    }

      

  • 相关阅读:
    BZOJ 2006: [NOI2010]超级钢琴 [ST表+堆 | 主席树]
    CF 741D. Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths [dsu on tree 类似点分治]
    CF 716E. Digit Tree [点分治]
    CF 291E. Tree-String Problem [dfs kmp trie图优化]
    CF 208E. Blood Cousins [dsu on tree 倍增]
    CF 246E. Blood Cousins Return [dsu on tree STL]
    CF 570D. Tree Requests [dsu on tree]
    [dsu on tree]【学习笔记】
    测试markdown
    BZOJ 1969: [Ahoi2005]LANE 航线规划 [树链剖分 时间倒流]
  • 原文地址:https://www.cnblogs.com/sharpest/p/9869459.html
Copyright © 2011-2022 走看看