zoukankan      html  css  js  c++  java
  • 获取Spring容器中的Bean协助调试

    在使用Spring进行开发时,有时调bug真的是很伤脑筋的一件事,我们可以通过自定义一个监听器来获取Spring容器中的Bean实例来协助我们调试。

    第一步:编写自定义监听器

    /**
     * 监听servletContext域中属性发生变化的监听器
     * @author Mr.Song
     */
    public class ServletContextAttributeListenerImpl 
                            implements ServletContextAttributeListener{
        /**
         * 存入应用域中时
         * @param scab
         */
        @Override
        public void attributeAdded(ServletContextAttributeEvent scab) {
            //1.取出ServletContext对象
            ServletContext context = scab.getServletContext();
            //2.取出spring的ioc容器(查看源码得知其key)
            WebApplicationContext wac = (WebApplicationContext)context.getAttribute
                (WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            //3.取出所有的bean名称
            String[] names = wac.getBeanDefinitionNames();
            for(String name : names){
                System.out.println(name);
            }
        }
        @Override
        public void attributeRemoved(ServletContextAttributeEvent scab) {}
        @Override
        public void attributeReplaced(ServletContextAttributeEvent scab) {}
    }

    第二步:在web.xml中配置监听器

    <listener>
       <listener-class>cn.dintalk.web.listeners.ServletContextAttributeListenerImpl</listener-class>
    </listener>

    如此,我们便可观察Spring容器中Bean实例创建的情况了。

    关注微信公众号,随时随地学习

  • 相关阅读:
    Windows 2008R2 安装PostgreSQL 11.6
    Redis-基础介绍
    SQL Server中的GAM页和SGAM页
    linux读写相关
    String 和 Stringbuild
    JVM(六)如何执行方法调用
    dubbo学习(三)实现细节
    dubbo学习(二)SPI
    spring boot
    MySQL学习(二十一)锁
  • 原文地址:https://www.cnblogs.com/dintalk/p/10911401.html
Copyright © 2011-2022 走看看