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){
            // 初始化动作
            // 定时器。。。。
            // 初始化业务数据
            // 某些保护
            // 注册等等操作
        }
    }
}

或者更简单一点

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component("SystemStartUpEvent")
@Slf4j
public class SystemStartUpEvent implements ApplicationListener<ContextRefreshedEvent> {

    private boolean startUp = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        if (!startUp){
            startUp = true;
            // 其他初始化业务代码

        }
    }
}
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值