Spring boot中CommandLineRunner的使用

导读:本篇文章讲解 Spring boot中CommandLineRunner的使用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com


背景

日常开发中有可能需要实现项目启动后执行的功能,比如特殊数据处理,权限控制等。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...");
    }
}

在这里插入图片描述


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119794.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!