Runner
CommandLineRunner
ApplicationRunner
两者作用:
能够在容器启动完成的时候执行run()里面的逻辑
适用场景:
需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。
实际使用:通过该接口来实现服务刚启动重新加载redis
不同之处:
这两个接口的不同之处在于:
- ApplicationRunner中run方法的参数为ApplicationArguments,
- CommandLineRunner接口中run方法的参数为String数组。
ComandLineRunner
@Component
public class TestImplCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("<<<<<<<<<<<<这个是测试CommandLineRunn接口>>>>>>>>>>>>>>");
}
}
String… args参数,是用户在启动Application的时候,通过Run Configurations中的Program Arguments添加的参数(参数格式为KV格式,类似于–foo=bar)
edward female 空格就相当于一个分隔符
ApplicationRunner
@Component // 需要添加组件管理,加入到psirng容器中
public class TestImplApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(args);
System.out.println("这个是测试ApplicationRunner接口");
}
}
@Order
如果有多个实现类,需要按一定的顺序执行。可以在实现了上加上@Order注解,
@Order(value = int)
SpringBoot 会按照@Order中的value值从小到大进行执行