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();
最新文章
- HQL查询——select子句
- junit
- 阿里云yum源
- log_slave_updates在线修改
- Hibernate学习
- 在egret中使用protobuf
- LeetCode 上最难的链表算法题,没有之一!
- select top 1 和select top 1 with ties * from SC 的区别
- 剑指offer用位运算实现两个数相加,及python相关的位操作
- Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring
- lombok标签之@Data @AllArgsConstructor @@NoArgsConstructor -如何去除get,set方法。@Data注解和如何使用,lombok
- HTML中 javascript 相对根路径问题
- 关于STL容器
- 动态产生DataSource------待整理
- invalid bound statement (not found)解决办法
- dig命令详解
- [转]hive中自定义函数(UDAF)实现多行字符串拼接为一行
- Java 多线程编程知识详解
- LoadLinked/StoreConditional (LL/SC)
- 启用lazyload插件,减少图片加载
热门文章
- django shell 集合
- ArchLinux 下架设PPTPD VPN服务
- 修改mysql默认字符集的方法
- 挑选分组中top1
- 【软件分析与挖掘】A Comparative Study of Supervised Learning Algorithms for Re-opened Bug Prediction
- ThinkJS 项目用 WebStorm 来设置断点与调试
- 简单设置 navgationbar(导航栏) 的 title 字体跟颜色
- jQuery手机端上拉刷新下拉加载更多页面
- MVVMlight框架应用:Data Binding、Command
- 【原创】C#搭建足球赛事资料库与预测平台(5) 赔率数据表设计1