標籤:
有些時候,尤其是在開發應用程式框架的時候,由於某些原因無法或者很難重啟tomcat或者reload應用,但是配置又需要動態生效,這個時候通常希望通過reload spring applicationcontext的方式來重新載入配置,比如資料來源的動態配置。
1、在web.xml配置監聽器ContextLoaderListener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
這一步不配置會導致WebApplicationContextUtils.getWebApplicationContext為空白,因為是listener完成上下文和servlet的綁定關係。
2、
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(request.getSession()
.getServletContext());
if (context.getParent() != null) {
((AbstractRefreshableApplicationContext) context.getParent())
.refresh();
}
((AbstractRefreshableApplicationContext) context).refresh();
========上面的第2步只正確了1/3,要完全正確,請參考如下:
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext(),"org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC"); -- springMVC為web.xml中對應servlet的名稱,正確的順序是先擷取dispatchservet對應的context,然後得到root,重新整理則先root,後dispatchservlet。
if (context.getParent() != null) {
((AbstractRefreshableApplicationContext) context.getParent()).refresh(); --
((AbstractRefreshableApplicationContext) context).refresh();
//重新載入並開啟資料來源,隨便操作下即可,防止第一次訪問時拋異常
metadataDAO.queryAppname();
============記憶不好了,順便記錄下:
擷取dispatchservlet對應的applicationcontext,WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext(),"org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC");
擷取root對應的applicationcontext,以下三種都可以:
WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext(),org.springframework.web.context.WebApplicationContext.ROOT);
WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext(),"org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC").getParent();
spring編程式重新整理/重新載入applicationcontext/dispatchservlet(正確版)