spring event事件(四)内部事件(1)ApplicationReadyEvent

一、介绍

1、简介

ApplicationReadyEvent 是 Spring Boot 提供的一个事件,它表示:整个 Spring 应用上下文已完全启动,Spring Boot 应用已准备好接受请求。

2、场景用途

通常用于在 Spring Boot 启动完成后执行一些初始化逻辑,例如:

  • 启动额外的线程、定时任务

  • 连接外部服务(如 HTTP、MQ、WebSocket)

  • 加载插件

  • 打印启动信息

二、使用方法

1、方法1——监听 ApplicationReadyEvent 事件
@Component
public class MyStartupRunner implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.out.println("✅ Application is ready.");
        // 可以安全地使用 Spring 容器中的 Bean
        ApplicationContext context = event.getApplicationContext();
        MyService myService = context.getBean(MyService.class);
        myService.doSomething();
    }
}

2、方法2——使用 @EventListener 更简洁

@Component
public class StartupListener {

    @EventListener
    public void onApplicationReady(ApplicationReadyEvent event) {
        System.out.println(" App is fully ready");
        // 比如:启动插件的 HTTP 服务
    }
}

三、与其他启动事件的对比

事件 含义
ApplicationStartingEvent 应用刚启动,还未创建上下文
ApplicationPreparedEvent 上下文已创建但未刷新
ContextRefreshedEvent Spring 容器刷新完成
ApplicationReadyEvent Spring Boot 应用完全启动并就绪
ApplicationFailedEvent 启动失败

你可能感兴趣的:(#,Spring,spring,java,mysql)