1、Spring 基于监听 ContextRefreshedEvent 事件,在应用启动后完成初始化操作。Spring Boot 中也能使用这种方式。 2、Spring Boot 提供了 ApplicationRunner 和 CommandLineRunner 用于完成启动后的初始化工作,我们只要实现继承这个接口并实现其中的 run 方法就可以了。 3、ApplicationRunner 和 CommandLineRunner 都可以获得...
我们将关注的是ApplicationReadyEvent,这是一个 Spring Boot 应用启动完成时会触发的事件。 2. 使用ApplicationListener监听事件 在Spring Boot 中,可以通过实现ApplicationListener接口或使用@EventListener注解来监听特定事件。下面是一个基本的示例,演示如何在应用启动后执行一些操作。 2.1 使用ApplicationListener 以下是一个...
ContextRefreshedEvent:context刷新事件 在Spring 应用上下文(ApplicationContext)刷新之后会发布此事件 context刷新完成也就代表容器初始化完成,此时一般监听到此事件后进行一些系统初始业务操作,比如缓存、启动定时任务、开启线程等 ServletWebServerInitializedEvent: Web 服务器初始化事件 springboot项目在tomcat启动之后,会发布...
在Spring Boot应用程序中编写一个定时任务,定时执行后续操作。 @Component public class MyScheduledTask { @Scheduled(fixedRate = 10000) // 每隔10秒执行一次 public void doSomething() { // 在这里编写您需要执行的逻辑 } } 复制代码 通过以上几种方式,您可以在Spring Boot应用程序启动完成后执行您需要的后续...
ContextRefreshedEvent 事件发生在容器初始化完毕后。此时 Spring 已经将所有的 bean 被成功加载,我们可以在这个监听器中注入我们要用到的 bean,就像写正常的业务代码一样,完成启动后的初始化任务。 监听ContextRefreshedEvent 事件的方式在 Spring 和 Spring Boot 中都行的通。不仅如此,我们还可以监听各种的 Application...
Spring Boot 启动事件顺序 1、ApplicationStartingEvent 这个事件在 Spring Boot 应用运行开始时,且进行任何处理之前发送(除了监听器和初始化器注册之外)。 2、ApplicationEnvironmentPreparedEvent 这个事件在当已知要在上下文中使用 Spring 环境(Environment)时,在 Spring 上下文(context)创建之前发送。
// 在这里编写需要在应用启动后执行的逻辑 } } 4. 使用Spring Boot的ApplicationRunner或CommandLine...
1. SpringBoot启动流程与启动事件的对应关系 starting() 对应 ApplicationStartingEvent environmentPrepared() 对应 ApplicationEnvironmentPreparedEvent contextPrepared() 对应 ApplicationContextInitializedEvent contextLoaded() 对应 ApplicationPreparedEvent started() 对应 ApplicationStartedEvent ...
1.spring boot 事件 ApplicationFailedEvent事件: 为springboot启动异常时的操作 ApplicationPreparedEvent事件: 上下文准备事件,但此时bean没有完全加载完成 ApplicationStartedEvent事件:spring boot已启动时执行的事件 ApplicationStartingEvent事件:spring boot启动开始则触发 ...