ApplicationReadyEvent
是 Spring Boot 提供的一个事件,它表示:整个 Spring 应用上下文已完全启动,Spring Boot 应用已准备好接受请求。
通常用于在 Spring Boot 启动完成后执行一些初始化逻辑,例如:
启动额外的线程、定时任务
连接外部服务(如 HTTP、MQ、WebSocket)
加载插件
打印启动信息
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 |
启动失败 |