Skip to content

9大事件与探针

各种回调和监听器

1、各种回调监听器

  • BootstrapRegistryInitializer: 感知引导初始化

    • META-INF/spring.factories
    • 创建引导上下文 bootstrapContext 的时候触发
    • 场景 : 进行密钥对授权
  • ApplicationContextInitializer: 感知 IOC 容器初始化

    • META-INF/spring.factories
  • ApplicationListener: 感知全阶段 : 基于事件机制,感知事件

    • @bean@EventListener
    • SpringApplication.addListenners(...)SpringApplicationBuilder.listeners(...)
    • META-INF/spring.factories

image-20241119111539706

  • SpringApplicationRunListener: 感知全阶段生命周期 + 各阶段都可自定义操作
    • META-INF/spring.factories
  • ApplicationRunner: 感知特定阶段 ---- 感知应用就绪
    • @Bean
  • CommandLineRunner: 感知特定阶段 --- 感知应用就绪
    • @Bean

最佳实战:

  • 如下项目启动前做事: BootstrapRegistryInitializerApplicationContextInitializer

  • 如果想要在项目启动完成后做事: ApplicationRunnerCommandLineRunner

  • 如果干涉生命周期做事: SpringApplicationRunListener

  • 如果想用事件机制: ApplicationListener

生命周期流程.png

生命周期流程代码截图.png