CommandLineRunner接口介绍

本文介绍了SpringBoot中的CommandLineRunner接口,它在容器启动后最后回调,用于添加启动时的处理逻辑。通过示例展示了如何实现接口并控制执行顺序。同时对比了ApplicationRunner接口,分析了ApplicationArguments对象,用于解析main方法参数,并提供了源码分析,帮助理解如何获取和使用参数。
摘要由CSDN通过智能技术生成

CommandLineRunner接口介绍

  CommandLineRunner接口是在容器启动成功后的最后一步回调(类似开机自启动)。

1. CommandLineRunner接口使用

  • 写一个类,实现CommandLineRunner接口,将该类注入到Spring容器中;
  • 可以通过@Order注解(属性指定数字越小表示优先级越高)或者Ordered接口来控制执行顺序。

例如,我们自定义两个类,实现CommandLineRunner接口,实现run方法,在run方法中添加处理逻辑。

@Order(5)
@Component
public class AppStartReport implements CommandLineRunner {
   

    @Override
    public void run(String... args) throws Exception {
   
        System.out.println("AppStartReport : 项目成功启动------------------");
    }
}
@Order(2)
@Component
public class AppStartReport2 implements CommandLineRunner {
   

    @Override
    public void run(String... args) throws Exception {
   
        System.out.println("AppStartReport2 : 项目成功启动------------------");
    }
}

项目启动效果如下,AppStartReport2 较AppStartReport 先执行:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值