zoukankan      html  css  js  c++  java
  • Spring+ ApplicationListener

    有时候 需要在容器初始化完成后,加载些 代码字典或不常变的信息  放入缓存之类的,这里使用spring 初始化bean,并实例化

    1.创建一个ApplicationListener类

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    import org.springframework.stereotype.Component;
    
    
    @Component("aviatorRegisterConfigue")
    public class AviatorRegisterConfigue implements ApplicationListener<ContextRefreshedEvent> {// ContextRefreshedEvent为初始化完毕事件,spring还有很多事件可以利用
        private static final Logger LOG = LoggerFactory.getLogger(AviatorRegisterConfigue.class);
        
        /**
         * 当一个ApplicationContext被初始化或刷新触发
         */
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
                            
                //放入代码字典操作
                LOG.info("redis缓存加载成功"); 
            }
        }
    
    }

    特别注意 event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")  这里是防止 初始化完成 操作执行2次,原因是

    在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet  context(作为root application context的子容器)。

    这种情况下,就会造成onApplicationEvent方法被执行两次。

  • 相关阅读:
    性能测试入门(三)线程组设置详解
    P3052 [USACO12MAR]摩天大楼里的奶牛Cows in a Skyscraper
    P3047 [USACO12FEB]附近的牛Nearby Cows
    P2698 [USACO12MAR]花盆Flowerpot
    P2898 [USACO08JAN]haybale猜测Haybale Guessing
    P1782 旅行商的背包
    P3629 [APIO2010]巡逻
    P1065 作业调度方案
    P1640 [SCOI2010]连续攻击游戏
    P2590 [ZJOI2008]树的统计
  • 原文地址:https://www.cnblogs.com/zwdx/p/8393099.html
Copyright © 2011-2022 走看看