【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 里的对应方法才会执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值