作用
CommandLineRunner 接口和 ApplicationRunner 接口是在容器启动成功后的最后一步回调,可以在项目成功启动后做一些检查工作或执行一些任务。如果多个检查工作需要按照一定的顺序去执行,那么就需要在实体类上使用一个 @Order 注解(或者实现 Order 接口)来表明顺序(order 值越小越先执行,默认 2147483647,最后执行)
- CommandLineRunner 用法
package com.just;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(JSONObject.toJSONString(args)); //["program.start.success!!!"]
}
}
- ApplicationRunner 用法
package com.just;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class StartApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(JSONObject.toJSONString(args)); //["program.start.success!!!"]
}
}
原理
源码
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
// 获取所有实现ApplicationRunner接口的类
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
// 获取所有实现CommandLineRunner接口的类
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
// 按照order排序
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) {
// 执行排完序的方法
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
package org.springframework.boot;
import java.util.List;
import java.util.Set;
// 获取启动参数的接口
public interface ApplicationArguments {
String[] getSourceArgs();
Set<String> getOptionNames();
boolean containsOption(String name);
List<String> getOptionValues(String name);
List<String> getNonOptionArgs();
}
添加项目启动参数
- 方法一:如果使用 idea。(1)点击 Edit Configurations 窗口;(2)Program arguments 即 main 方法的 args 参数传入
- 方法二:直接在项目启动参数添加命令行
–program.start.success!!!
关于 order 接口
public interface Ordered {
int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
int getOrder();
}