ApplicationListener<ContextRefreshedEvent> 初始化动作接口学习及理解

ApplicationListener< ContextRefreshedEvent> 说明

ApplicationListener< ContextRefreshedEvent> 一般被用于在项目初始化动作完成后执行的自己业务拓展动作,简单来说就是 实现该接口的 类将会需要重写 某一方法,作为应用初始化完毕后执行的动作。

需要注意的是
先有 InitializingBean,后有 ApplicationListener< ContextRefreshedEvent>,也就是在IOC将所有的bean 都处理完成后会触发的时间,由于在 WEB (spring mvc)项目中存在两个context,即一个 root application context 和自己项目的 projectName-servlet context(projectName-servlet context 会作为 root application context 的子容器),会导致实现了此接口的方法被执行两次,学习后发现了以下处理方式。

示例代码如下:

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class SystemInitListencer implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // WEB(spring mvc) 环境防止重复触发
        if (contextRefreshedEvent.getApplicationContext().getParent() == null){
            // 初始化动作
            // 定时器。。。。
            // 初始化业务数据
            // 某些保护
            // 注册等等操作
        }
    }
}

版权声明:本文为weixin_44131922原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。