SpringBoot CommandLineRunner详解

简述

  如果在项目中,我们想在项目启动的时候干一些事情,比如从数据库加载一些数据、提前加载加密证书,并且这些功能只干一次

  我们就可以使用CommandLineRunner完成我们的需求,我们可以继承CommandLineRunner接口,实现其run方法

  这样在springboot启动的时候会自动运行我们实现的run方法

普通地实现run方法  

  下面这个springboot启动类执行后就会调用run方法,run方法只执行一次

复制代码
@SpringBootApplication
public class CommandLineRunnerApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(CommandLineRunnerApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("abc");
    }
}
复制代码

根据springboot启动参数控制

  其中的run方法的入参就是springboot启动的时候的参数,我们可以手动根据参数判断来干些什么事情

复制代码
@SpringBootApplication
public class CommandLineRunnerApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(CommandLineRunnerApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        if (Objects.equals(args[0], "abc")) {
            System.out.println("foo bar");
        }
    }
}
复制代码

多个CommandLineRunner的执行顺序

References

https://blog.csdn.net/chenlixiao007/article/details/113881768

https://developer.aliyun.com/article/897438

posted @   艾尔夏尔-Layton  阅读(281)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
历史上的今天:
2020-03-17 matlab初学第四课•Layton大讲堂之 matlab简单的判断流程控制
2019-03-17 第二章内容小结以及资料分享
点击右上角即可分享
微信分享提示