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()
 }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM