Spring Boot 2 实战:自定义启动运行逻辑

本文介绍了如何在Spring Boot 2中使用CommandLineRunner和ApplicationRunner接口来实现在项目启动后执行自定义逻辑,包括不同优先级的实现,并探讨了两者的区别以及如何读取命令行启动参数。此外,文章还提供了实践操作示例和注意事项。
摘要由CSDN通过智能技术生成

1. 前言

不知道你有没有接到这种需求,项目启动后立马执行一些逻辑。比如缓存预热,或者上线后的广播之类等等。可能现在没有但是将来会有的。想想你可能的操作, 写个接口上线我调一次行吗?NO!NO!NO!这种初级菜鸟才干的事。今天告诉你个骚操作使得你的代码更加优雅,逼格更高。

2. CommandLineRunner 接口

 package org.springframework.boot;

 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;

 }

CommandLineRunner 作用是当springApplication 启动后,在同一应用上下文中定义的多个 CommandLineRunner 类型的 Spring Bean 按照标记顺序执行。如果你想替代以数组方式接收 args 参数 可以用 另一个接口代替 org.springframework.boot.ApplicationRunner

talk is cheap show your code 下面我就来操作一波演示一下。

2.1 优先级比较高的 CommandLineRunner 实现

 package cn.felord.begin;

 import lombok.extern.slf4j.Slf4j;
 import org.springframework.boot.CommandLineRunner;
 import org.springframework.core.Ordered;
 import org.springframework.stereotype.Component;

 /**
  * 优先级比较高 通过实现接口{@link Ordered}的方式 来指定优先级
  *  命令行测试参数     --foo=bar --dev.name=码农小胖哥  java,springboot
  * @author Felordcn
  * @since 2019/6/17 23:06
  */
 @Sl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值