zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    BeautifulSoup模块
    爬取校花网视频
    爬虫基本原理
    python学习笔记-50 使用SQLAlchemy
    python学习笔记-49 使用MySQL
    PTA天梯 L3-007 天梯地图
    VS2013 创建ASP.NET MVC 4.0 未指定的错误(异常来自HRESULT: 0x80004005(e_fail))
    动态规划--新手
    文件上传绕过
    C# → 数据库
  • 原文地址:https://www.cnblogs.com/zhjh256/p/5771713.html
Copyright © 2011-2022 走看看