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