使用场景:
如果我们需要在 SpringApplication 启动完成后自动运行一些特定的代码,我们可以使用这两个接口,这两个接口都是函数式接口有且只有一个run方法,通过实现这两个接口,我们可以在run方法中编写一些代码,这个run方法会在SpringApplication应用启动完成之后自动的执行,同时为了确保实现了这两个接口的实现类能够自动生效,我们必须将该类注册成Bean组件,此外,我们也可以继续通过实现Ordered接口或者通过@Order注解来指定run方法的执行顺序,其中Order的值越小越先执行,参考如下:
@Component
public class TestApplicationRunner implements ApplicationRunner, Ordered {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("【ApplicationRunner】这是使用ApplicationRunner接口实现的代码执行,Order值为0");
}
@Override
public int getOrder() {
return 0;
}
}
@Order(value = 1)
@Component
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("【CommandLineRunner】这是使用CommandLineRunner接口实现的代码执行,Order值为1");
}
}
程序启动结果:
这两个接口的方法中都有一个args参数,这个参数表示的是springboot应用启动时的命令行参数,只不过ApplicationRunner接口中该参数是一个ApplicationArguments接口引用,在获取命令行参数时需要通过调用接口中的getSourceArgs()方法来获取真正的命令行参数;CommandLineRunner接口中的args参数就是命令行参数。参看示例如下:
命令行参数配置:
ApplicationRunner接口输出命令行参数:
@Component
public class CustomeApplicationRunner implements ApplicationRunner, Ordered {
// 需要通过调用getSourceArgs()方法获取命令行参数
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("CustomeApplicationRunner命令行参数:"+Arrays.toString(args.getSourceArgs()));
}
// 排序,越小越先执行
@Override
public int getOrder() {
return 0;
}
}
CommandLineRunner接口输出命令行参数:
@Component
public class CustomeCommandLineRunner implements CommandLineRunner, Ordered {
// args直接就是命令行参数
@Override
public void run(String... args) throws Exception {
System.out.println("CustomeCommandLineRunner命令行参数:"+Arrays.toString(args));
}
//排序
@Override
public int getOrder() {
return 1;
}
}
输出结果: