spring boot2 (29)-ApplicationRunner和CommandLineRunner初始化

上一篇讲了缓存,当访问缓存时,发现没有数据就查询数据库并写入缓存。也可以在项目启动时就直接查询并写入缓存,以免用户请求的时候再去查询,此时就可以使用ApplicationRunner或者CommandLineRunner

CommandLineRunner

用法很简单,只要实现该接口,启动项目后会立即使用run方法,args是启动参数。

@Component
public class InitialRunner1 implements CommandLineRunner {

	public void run(String... args) throws Exception {
		System.out.println("初始化业务");

ApplicationRunner

和CommandLineRunner用法是一样的,只是对args启动参数进行了封装,下面会讲

@Component
public class InitialRunner2 implements ApplicationRunner {

	public void run(ApplicationArguments args) throws Exception {
		System.out.println("初始化业务");

ApplicationArguments参数

--param1=value1
--param1=value2
--param2=value3

在eclipse运行配置中添加以上启动参数,注意:其中有两个param1参数,参数名以--开头。


修改run方法代码,getOptionValues方法得到的是list,其中包含param1参数的所有值,value1和2

public void run(ApplicationArguments args) throws Exception {
		System.out.println(args.getOptionValues("param1").get(0));
		System.out.println(args.getOptionValues("param1").get(1));
		System.out.println(args.getOptionValues("param2").get(0));
	}

运行结果:


@Order 执行顺序

上面声明了两个初始类,我们需要它们按照一定的顺序来执行,则可以使用@Order注解,如下:

@Order(1)
@Component
public class InitialRunner1 implements CommandLineRunner 
@Order(2)
@Component
public class InitialRunner2 implements ApplicationRunner

@Order参数数字越小的先执行

猜你喜欢

转载自blog.csdn.net/wangb_java/article/details/80372004