CommandLineRunner详解

背景

项目启动之前,预先加载数据。比如,权限容器、特殊用户数据等。通常我们可以使用监听器、事件来操作。但是,springboot提供了一个简单的方式来实现此类需求,即,CommandLineRunner。

技术储备

先了解一下这个类

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 * <p>
 * If you need access to {@link ApplicationArguments} instead of the raw String array
 * consider using {@link ApplicationRunner}.
 *
 * @author Dave Syer
 * @see ApplicationRunner
 */
@FunctionalInterface
public interface CommandLineRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}

文档中,我们可以知道以下几点。

  1. 这是一个接口,用户可以自定义实现该接口,具体实现run方法
  2. 任何在上下文容器之内的bean都可以实现run方法
  3. 如果在上下文中,存在多个该接口实现类,可以通过@order注解,指定加载顺序

所以我们基本上大概已经了解了这个接口的作用以及用法。

案例说明

分别定义一个数据加载类MyStartupRunner1,排序为2;另一个数据加载类MyStartupRunner2,排序为1。看看它们记载数据的顺序。
MyStartupRunner1.java

	@Component
	@Order(value = 2)
	public class MyStartupRunner1 implements CommandLineRunner{
    @Override
    public void run(String... strings) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 MyStartupRunner1 order 2 <<<<<<<<<<<<<");
	    }
	}

MyStartupRunner2.java

	@Component
	@Order(value = 1)
	public class MyStartupRunner2 implements CommandLineRunner {
	@Override
		public void run(String... strings) throws Exception {
    		System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 MyStartupRunner2 order 1 <<<<<<<<<<<<<");
    	}
	}

运行结果输出:
这里写图片描述

我们可以看出,数据加载的顺序与注解@Order的value有关!

完!

  • 35
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿呆编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值