springboot-CommandLineRunner-启动时执行任务 一、CommandLineRunner的作用 二、如果有多个类实现CommandLineRunner接口,如何保证顺序 三、CommandLineRunner接口在SpringBoot启动时执行的顺序 四、Springboot中的类似接口

项目启动后,执行run方法中的代码。

如下所示:

package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
  }
}

二、如果有多个类实现CommandLineRunner接口,如何保证顺序

使用@Order 注解,通过源码查看,order的值越小优先级越高

如下所示:

package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服务启动执行 2222 <<<<<<<<<<<<<");
    }
}    

三、CommandLineRunner接口在SpringBoot启动时执行的顺序

CommandLineRunner接口的run()方法会在spring bean初始化之后,SpringApplication run之前执行,可以控制在项目启动前初始化资源文件,比如初始化线程池,提前加载好加密证书等
 

四、Springboot中的类似接口

ApplicationRunner