spring編程式重新整理/重新載入applicationcontext/dispatchservlet(正確版)

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.