spring编程式刷新/重新加载applicationcontext/dispatchservlet(正确版)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了spring编程式刷新/重新加载applicationcontext/dispatchservlet(正确版),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2058字,纯文字阅读大概需要3分钟。
内容图文
有些时候,尤其是在开发应用框架的时候,由于某些原因无法或者很难重启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();
原文:http://www.cnblogs.com/zhjh256/p/5771713.html
内容总结
以上是互联网集市为您收集整理的spring编程式刷新/重新加载applicationcontext/dispatchservlet(正确版)全部内容,希望文章能够帮你解决spring编程式刷新/重新加载applicationcontext/dispatchservlet(正确版)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。