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 @ 2023-03-17 14:51  艾尔夏尔-Layton  阅读(182)  评论(0编辑  收藏  举报