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 @   zhjh256  阅读(2677)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示