前言
CommandLineRunner和ApplicationRunner可以让任务在Spring boot程序启动时执行,这常用来做一些初始化的操作,如果有多个初始化操作,可以用@Order注解来排序,如果同时定义了CommandLineRunner和ApplicationRunner,排序时是并列的关系,@Order对他们同时起效。除了以类的形式出现,我们还可以定义返回值为CommandLineRunner和ApplicationRunner的方法,并且给方法上加上@Bean的注解。以方法定义的CommandLineRunner和ApplicationRunner会优先执行ApplicationRunner,并且@Bean注解的方法运行在之前提到的类执行之后。实现CommandLineRunner的类的run方法传参是可变String数组,实现ApplicationRunner的类的run方法传参是ApplicationArguments,而注解为@Bean的commandLineRunner和applicationRunner传参为ApplicationContext。
代码
package com.example.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.stream.Collectors;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("commandLineRunner方法检查一下Spring Boot提供的bean:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
//System.out.println(beanName);
}
};
}
@Bean
public ApplicationRunner applicationRunner(ApplicationContext ctx){
return args -> {
System.out.println("applicationRunner方法检查一下Spring Boot提供的bean:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
//System.out.println(beanName);
}
};
}
@Component
@Order(value = 1)
public class MyStartupRunner1 implements CommandLineRunner{
@Override
public void run(String... strings) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 CommandLineRunner1 order 1 <<<<<<<<<<<<<");
}
}
@Component
@Order(value = 2)
public class MyStartupRunner2 implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
String strArgs = Arrays.stream(strings).collect(Collectors.joining("|"));
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 CommandLineRunner2 order 2 <<<<<<<<<<<<<"+strArgs);
}
}
@Component //此类一定要交给spring管理
@Order(value=4) //首先执行
public class ConsumerRunnerA implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("需要在springBoot项目启动时执行的代码 ApplicationRunner order 4---");
}
}
@Component //此类一定要交给spring管理
@Order(value=3) //其次执行
public class ConsumerRunnerB implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception{
//代码
System.out.println("需要在springBoot项目启动时执行的代码 ApplicationRunner order 3---");
}
}
}
执行结果

278

被折叠的 条评论
为什么被折叠?



