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();

 

posted @ 2016-08-15 08:54  zhjh256  阅读(2637)  评论(0编辑  收藏  举报