Spring boot中CommandLineRunner的使用


背景

日常开发中有可能需要实现项目启动后执行的功能,比如特殊数据处理,权限控制等。Spring boot提供了一种简单的实现方案。即CommandLineRunner


CommandLineRunner

/**
 * 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
 * @since 1.0.0
 * @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;

}

通过看源码,可以得知:

  • 这是一个接口,我们可以自定义实现类来实现该接口及实现run方法
  • 多个实现类可以被同时执行在同一个spring上下文中并且执行顺序是以order注解的参数顺序一致

案例说明

1.单个实现类

@Component
@Slf4j
public class InitService implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
   
        log.info("项目启动初始化...");
    }
}

在这里插入图片描述

2.多个实现类

多个实现类的时候,如何保证顺序呢?

SpringBoot在项目启动后会遍历所有实现CommandLineRunner的实体类并执行run方法,如果需要按照一定的顺序去执行,那么就需要在实体类上使用一个@Order注解(或者实现Order接口)来表明顺序

@Component
@Slf4j
@Order(value = 2)
public class InitService implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("项目启动初始化1...");
    }
}
@Component
@Slf4j
@Order(value = 1)
public class InitService2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
       log.info("项目启动初始化2....");
    }
}
@Component
@Slf4j
@Order(value = 3)
public class InitService3 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
      log.info("项目启动初始化3...");
    }
}

在这里插入图片描述


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只努力的笨笨熊

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

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

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

打赏作者

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

抵扣说明:

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

余额充值