當 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 更方便:
WebApplicationContext wac =WebApplicationContextUtils.
getWebApplicationContext(servletContext);
當 ServletContext 屬性列表中不存在 WebApplicationContext 時,getWebApplicationContext() 方法不會拋出異常,它簡單地返回 null。如果後續代碼直接訪問返回的結果將引發一個 NullPointerException 異常,而 WebApplicationContextUtils 另一個 getRequiredWebApplicationContext(ServletContext sc) 方法要求 ServletContext 屬性列表中一定要包含一個有效的 WebApplicationContext 對象,否則馬上拋出一個 IllegalStateException 異常。我們推薦使用後者,因爲它能提前發現錯誤的時間,強制開發者搭建好必備的基礎設施。
實例:
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()
}
}
使用spring的工具類獲得容器中的bean對象
public static IMail getMail(HttpServletRequest request)throws Exception{
ServletContext sc = request.getSession().getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
IMail mail = (IMail) ac.getBean("emailImpl");
return mail;
}