java_SpringBoot启动项目初始化数据 ApplicationListener<ContextRefreshedEvent>使用详解

目录

一、介绍说明

二、示例


一、介绍说明

    1、ApplicationListener介绍
    ApplicationListener是Spring 框架中的监听和处理应用事件。

    2、ApplicationListener的工作原理
    ApplicationListener的工作原理基于发布-订阅模式。事件发布者(ApplicationEventPublisher)发布事件,而事件监听器(实现了ApplicationListener接口的类)则监听这些事件。当事件发生时,所有注册了该事件的监听器都会被调用,执行相应的操作。从而实现了系统的解耦和可扩展性‌。


    3、ContextRefreshedEvent介绍
    ContextRefreshedEvent事件是一个重要的事件。
    A:在spring 应用上下文初始化完成后触发。

    B:在spring应用上下文被刷新时:例如调用refresh()方法。


二、示例

import com.test.task.TaskManager;
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;

@Slf4j
@Component
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent>{


    @Autowired
    private TaskManager taskManager;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            //调用初始化方法
            taskManager.init();
            log.info("初始化消息信息加载完毕--------------------");

        }catch (Exception e){
            log.error("启动服务出现异常,e=",e);
            //关闭程序
            System.exit(1);
        }
    }
}

注意事项:
1、实现ApplicationListener<ContextRefreshedEvent>接口

重写onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法。


2、onApplicationEvent方法中调用需要初始化的方法,并处理异常,异常时,关闭程式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软件开发老油条

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值