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

  • 相关阅读:
    华为超大云数据中心落地贵州,这些硬核技术有利支撑“东数西算”
    在高并发环境下该如何构建应用级缓存
    使用 Python Poetry 进行依赖管理
    AI新手语音入门:认识词错率WER与字错率CER
    一文带你了解什么是GitOps
    需求蔓延,常见但不正常,教你如何破
    云图说|初识ModelArts开发者生态社区——AI Gallery
    XML学习笔记:关于字符编码的理解~
    Python中单引号、双引号和三双引号的区别:
    LBFGS算法的使用~
  • 原文地址:https://www.cnblogs.com/zhjh256/p/5771713.html
Copyright © 2020-2023  润新知