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 更方便:

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()
}
}
原文地址:https://www.cnblogs.com/freemanabc/p/5457851.html