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

ApplicationListener<ContextRefreshedEvent>接口用于在Spring项目初始化完成后执行自定义业务操作。在Web(Spring MVC)环境中,由于存在root application context和servlet context,可能会导致初始化方法被调用两次。文中提供了两种解决方案,通过检查ApplicationContext的父容器或使用布尔标志避免重复执行。示例代码展示了如何实现和避免重复触发的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值