spring-boot 学习笔记之Runner

SpringBoot之Runner

如果想在SpringBoot容器启动后做一些事情,SpringBoot提供了两个回调类

  • CommandLineRunner : 执行参数为ApplicationArguments
    public interface ApplicationRunner {
       void run(ApplicationArguments args) throws Exception;
     }```
    
  • ApplicationRunner:执行参数为数组
    public interface CommandLineRunner {
       void run(String... args) throws Exception;
    }```
    

Demo如下:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
public class DefaultCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(getClass().getSimpleName());
    }
}
@Component
@Order(3)
public class Runner1 extends DefaultCommandLineRunner {

}
@Component
@Order(2)
public class Runner2 extends DefaultCommandLineRunner {

}
@Component
@Order(1)
public class Runner3 extends DefaultCommandLineRunner {

}
Paste_Image.png

Order排序小的执行顺序在前

你可能感兴趣的:(spring-boot 学习笔记之Runner)