◉◡◉ 您好,欢迎到访伊成个人站!

spring boot中的ApplicationRunner和CommandLineRunner

本文于1668天之前发表,文中内容可能已经过时。

导言

在某些场景中,可能会需要到项目启动完成之后就需要初始化数据,读取配置文件,数据库信息等等业务需求。在spring boot中已经给我们提供了
对应的接口,这两个接口是CommandLineRunner和ApplicationRunner。他们的执行时机为容器启动完成的时候。

这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,
而CommandLineRunner接口中run方法的参数为String数组。

ApplicationRunner

1
2
3
4
5
6
@Component
public class AppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("这个是测试ApplicationRunner接口");
}

CommandLineRunner

1
2
3
4
5
6
7
8
9
@Component
@Order(value = 1)
public class AgentApplicationRun implements CommandLineRunner {

@Override
public void run(String... strings) throws Exception {
System.out.println("这个是测试CommandLineRunner接口");
}
}

当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。
注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行

支付宝打赏 微信打赏