spring編程式刷新/重新加載applicationcontext/dispatchservlet(正確版)


有些時候,尤其是在開發應用框架的時候,由於某些原因無法或者很難重啟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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM