WebApplicationContextUtils是一個抽象類,其提供了一個很便利的方法來獲取spring應用的上下文即WebApplicationContext。
其中的靜態方法getWebApplicationContext(ServletContext sc),提供一個ServletContext 類型參數即可。
其原理十分簡單,在spring容器初始化的方法org.springframework.web.context.ContextLoader.initWebApplicationContext(ServletContext)中
通過servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);已經將WebApplicationContext的實例放入ServletContext 中了。
然后在工具類的org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(ServletContext)中就可以通過傳入的ServletContext參數獲取到WebApplicationContext實例了。
