【Spring】服务启动后指定命令实现方法

   阿丹:

        在一定的业务场景下,当一个服务进行启动了之后。需要让外界感知、或者需要注册的时候,就涉及到需要触发服务启动后实现的指令方法。

Spring Boot 启动项目后执行特定方法有以下几种常见方式:

  1. 使用注解 @PostConstruct

    • 在任何需要在构造器之后但在初始化完成之前执行逻辑的bean上使用此注解。这是最简单的一种方式,但要注意如果该方法执行时间过长,会阻止其他bean的初始化完成,进而延迟整个应用的启动。
1@Component
2public class StartupBean {
3
4    @PostConstruct
5    public void init() {
6        // 这里编写启动后需要执行的代码
7    }
8}
  1. 实现 CommandLineRunner 或 ApplicationRunner 接口

    • 这两种接口都提供了 run() 方法,会在所有Spring Beans初始化完成后并且应用程序准备好接收请求之前执行。
    • CommandLineRunner 是当程序是从命令行启动时有用,适合处理命令行参数。
    • ApplicationRunner 与之类似,但不依赖于命令行参数。
1@Component
2public class StartupRunner implements CommandLineRunner, ApplicationRunner {
3
4    @Override
5    public void run(String... args) { // CommandLineRunner
6        // 启动后执行的代码
7    }
8
9    @Override
10    public void run(ApplicationArguments args) { // ApplicationRunner
11        // 启动后执行的代码
12    }
13}
  1. 实现 ApplicationListener 并监听 ApplicationReadyEvent

    • 如果你想在应用完全启动并准备就绪后执行某些操作,可以实现 ApplicationListener 接口并监听 ApplicationReadyEvent。
1@Component
2public class StartupEventListener implements ApplicationListener<ApplicationReadyEvent> {
3
4    @Override
5    public void onApplicationEvent(ApplicationReadyEvent event) {
6        // 应用启动成功后执行的操作
7    }
8}
  1. 通过 Spring Boot 的事件机制注册监听器

    • 可以监听除了 ApplicationReadyEvent 之外的其他Spring Boot生命周期事件,比如 ContextRefreshedEvent 等。
  2. 使用 @EventListener 注解

    • 从Spring Framework 4.2开始,可以通过 @EventListener 注解直接在方法上声明监听某个事件,无需实现 ApplicationListener 接口
1@Component
2public class StartupEventHandler {
3
4    @EventListener
5    public void handleStartup(ApplicationReadyEvent event) {
6        // 应用启动成功后执行的操作
7    }
8}

执行顺序:

  • @PostConstruct 注解的方法首先执行。
  • 然后是实现了 CommandLineRunner 和 ApplicationRunner 接口的 bean 中的 run 方法,其执行顺序可通过实现 Ordered 接口或使用 @Order 注解来控制。
  • 当所有Spring Boot启动过程完成,并发出 ApplicationReadyEvent 时,实现了 ApplicationListener 的 bean 里的对应方法才会执行。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-26 19:18:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-26 19:18:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-26 19:18:03       82 阅读
  4. Python语言-面向对象

    2024-01-26 19:18:03       91 阅读

热门阅读

  1. C++实现模版模式 + 创建者模式的demo

    2024-01-26 19:18:03       50 阅读
  2. ffmpeg 实用命令 -- 设置预览图

    2024-01-26 19:18:03       52 阅读
  3. 每日OJ题_算法_二分查找③_力扣69. x 的平方根

    2024-01-26 19:18:03       58 阅读
  4. IDEA使用快捷键提炼函数(Extract Method)

    2024-01-26 19:18:03       49 阅读
  5. 字符串随机生成工具(开源)-Kimen(奇门)

    2024-01-26 19:18:03       48 阅读