Spring boot -- 初始化数据

在系统一开始加载的时候,需要初始化一些数据,例如文件的加载、数据库的初始化等操作,在spring 中 可以使用 Listener 进行解决,但是在spring boot  使用 CommandLineRunner 和  ApplicationRunner 来解决,两个类的用于基本一致,唯一不同的是参数

CommandLineRunner:Spring  boot  在启动的时候,会遍历该类的实现类

在项目启动的时候,会遍历该类的实现类,并且 会调用里面的run 方法,如果是多个 CommandLineRunner 可以使用@Order 来进行优先级的顺序,数字越小,优先级越高

@Component
@Order(1)
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.err.println("MyCommadLineRunner >>> " + Arrays.toString(args));
    }
}

程序的初始化参数设置

ApplicationRunner

@Component
@Order(3)
public class MyApplicationRunner1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> nonOptionArgs = args.getNonOptionArgs();
        System.err.println("MyApplicationRunner1  >> " +nonOptionArgs);
        Set<String> optionNames = args.getOptionNames();
        for (String optionName: optionNames) {
            System.err.println("key:"+optionName+">>>value :"+ args.getOptionValues(optionName));
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值