Spring+ ApplicationListener

2018-06-18 03:35:07来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

有时候 需要在容器初始化完成后,加载些 代码字典或不常变的信息  放入缓存之类的,这里使用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方法被执行两次。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:数据库分表之Mybatis+Mysql实践(含部分关键代码)

下一篇:maven项目引入外部jar包的三种方式