前言

一般项目中的初始化操作,初次遇见,妙不可言。如果你还有哪些方式可用于初始化操作,欢迎在评论中分享出来~

ApplicationRunner 和 CommandLineRunner

Spring Boot 应用,在启动的时候,如果想做一些事情,比如预先加载并缓存某些数据,读取某些配置等等。总而言之,做一些初始化的操作时,那么 Spring Boot 就提供了两个接口帮助我们实现。

这两个接口是:

  • ApplicationRunner 接口
  • CommandLineRunner 接口

源码如下:

ApplicationRunner

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 ApplicationRunner} beans can be defined
* within the same application context and can be ordered using the {@link Ordered}
* interface or {@link Order @Order} annotation.
*
* @author Phillip Webb
* @since 1.3.0
* @see CommandLineRunner
*/
@FunctionalInterface
public interface ApplicationRunner { /**
* Callback used to run the bean.
* @param args incoming application arguments
* @throws Exception on error
*/
void run(ApplicationArguments args) throws Exception; }

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
* @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; }

可以看到,这两个接口的注释几乎一模一样,如出一辙。大致的意思就是,这两个接口可以在 Spring 的环境下指定一个 Bean 运行(run)某些你想要做的事情,如果你有多个 Bean 进行指定,那么可以通过 Ordered 接口或者 @Order 注解指定执行顺序。

说白了,就是可以搞多个实现类实现这两个接口,通过 @Order 确定实现类的谁先运行,谁后运行

@Order

再看看 @Order 注解的源码:

/**
* {@code @Order} defines the sort order for an annotated component.
*
* <p>The {@link #value} is optional and represents an order value as defined in the
* {@link Ordered} interface. Lower values have higher priority. The default value is
* {@code Ordered.LOWEST_PRECEDENCE}, indicating lowest priority (losing to any other
* specified order value).
* ..... 省略剩下的注释
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order { /**
* The order value.
* <p>Default is {@link Ordered#LOWEST_PRECEDENCE}.
* @see Ordered#getOrder()
*/
int value() default Ordered.LOWEST_PRECEDENCE; }

Ordered.LOWEST_PRECEDENCE 的默认值是 Integer.MAX_VALUE

在顶部的注释中,可以知道,@Order 注解是给使用了 @Component 注解的 Bean 定义排序顺序(defines the sort order for an annotated component),然后 @Order 注解的 value 属性值越低,那么代表这个 Bean 有着更高的优先级(Lower values have higher priority)。

测试

分别写两个实现类,实现这两个接口,然后启动 Spring Boot 项目,看看执行顺序

ApplicationRunnerImpl:

@Slf4j
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("我正在加载 ------------------> ApplicationRunnerImpl");
}
}

CommandLineRunnerImpl:

@Slf4j
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("我正在加载 ------------------> CommandLineRunnerImpl");
}
}

控制台输出:

2023-03-26 15:46:38.344  INFO 25616 --- [           main] c.g.demo.init.ApplicationRunnerImpl      : 我正在加载 ------------------> ApplicationRunnerImpl
2023-03-26 15:46:38.344 INFO 25616 --- [ main] c.g.demo.init.CommandLineRunnerImpl : 我正在加载 ------------------> CommandLineRunnerImpl

可以看到,是 ApplicationRunnerImpl 先运行的,CommandLineRunnerImpl 后运行的。

我们给 CommandLineRunnerImpl 加上 @Order 注解,给其 value 属性设置 10:

@Slf4j
@Order(10)
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("我正在加载 ------------------> CommandLineRunnerImpl");
}
}

控制台输出:

2023-03-26 15:50:43.524  INFO 16160 --- [           main] c.g.demo.init.CommandLineRunnerImpl      : 我正在加载 ------------------> CommandLineRunnerImpl
2023-03-26 15:50:43.524 INFO 16160 --- [ main] c.g.demo.init.ApplicationRunnerImpl : 我正在加载 ------------------> ApplicationRunnerImpl

区别

回到这两个接口,看似一模一样,但肯定有小小区别的,最主要的区别就是接口的抽象方法的参数

ApplicationRunner:

  • void run(ApplicationArguments args) throws Exception;

CommandLineRunner:

  • void run(String... args) throws Exception;

具体来说,ApplicationRunner 接口的 run 方法中的参数为 ApplicationArguments 对象,该对象封装了应用程序启动时传递的命令行参数和选项。

CommandLineRunner 接口的 run 方法中的参数为 String 数组,该数组直接包含了应用程序启动时传递的命令行参数和选项。

测试

打印下命令行参数:

@Slf4j
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner: optionNames = " + args.getOptionNames() + ", sourceArgs = " + args.getSourceArgs());
}
}
@Slf4j
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner: " + Arrays.toString(args));
}
}

用 Maven 打包项目为 Jar 包,启动该 Jar 包:

// 使用 java -jar 启动,加上两个参数:name 和 description
java -jar demo-0.0.1-SNAPSHOT.jar --name=god23bin --description=like_me

输出:

ApplicationRunner: optionNames = [name, description]sourceArgs = [Ljava.lang.String;@5c90e579
CommandLineRunner: [--name=god23bin, --description=like_me]

最后的最后

由本人水平所限,难免有错误以及不足之处, 屏幕前的靓仔靓女们 如有发现,恳请指出!

最后,谢谢你看到这里,谢谢你认真对待我的努力,希望这篇博客对你有所帮助!

你轻轻地点了个赞,那将在我的心里世界增添一颗明亮而耀眼的星!

Spring Boot 中的 ApplicationRunner 和 CommandLineRunner的更多相关文章

  1. spring boot 中文文档地址

    spring boot 中文文档地址     http://oopsguy.com/documents/springboot-docs/1.5.4/index.html Spring Boot 参考指 ...

  2. Spring Boot 中初始化资源的几种方式(转)

    假设有这么一个需求,要求在项目启动过程中,完成线程池的初始化,加密证书加载等功能,你会怎么做?如果没想好答案,请接着往下看.今天介绍几种在Spring Boot中进行资源初始化的方式,帮助大家解决和回 ...

  3. Spring Boot 中初始化资源的几种方式

    假设有这么一个需求,要求在项目启动过程中,完成线程池的初始化,加密证书加载等功能,你会怎么做?如果没想好答案,请接着往下看.今天介绍几种在Spring Boot中进行资源初始化的方式,帮助大家解决和回 ...

  4. 在 Spring Boot 中使用 HikariCP 连接池

    上次帮小王解决了如何在 Spring Boot 中使用 JDBC 连接 MySQL 后,我就一直在等,等他问我第三个问题,比如说如何在 Spring Boot 中使用 HikariCP 连接池.但我等 ...

  5. spring boot(三):Spring Boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  6. Spring Boot中的事务管理

    原文  http://blog.didispace.com/springboottransactional/ 什么是事务? 我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合 ...

  7. Spring Boot中的注解

    文章来源:http://www.tuicool.com/articles/bQnMra 在Spring Boot中几乎可以完全弃用xml配置文件,本文的主题是分析常用的注解. Spring最开始是为了 ...

  8. 在Spring Boot中使用Https

    本文介绍如何在Spring Boot中,使用Https提供服务,并将Http请求自动重定向到Https. Https证书 巧妇难为无米之炊,开始的开始,要先取得Https证书.你可以向证书机构申请证书 ...

  9. Spring Boot中使用Swagger2构建强大的RESTful API文档

    由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...

  10. Dubbo在Spring和Spring Boot中的使用

    一.在Spring中使用Dubbo 1.Maven依赖 <dependency> <groupId>com.alibaba</groupId> <artifa ...

随机推荐

  1. Ubuntu系统运行Steam中VR游戏的相关软件环境配置说明

    ubuntu下的SteamVR(HTCVive)设置教程 贴吧链接     https://tieba.baidu.com/p/5333529880 运行SteamVR出现的一些问题解决方案参考链接  ...

  2. seleniumUI自动化学习记录

    2019.2.9 尝试了一个启动浏览器并打开指定网址的程序: 这里首先要注意的就是浏览器的版本和selenium jar包的版本必须符合才行,不然会报错 2019.9.16 必须要下载相应的chrom ...

  3. angular-gridster2使用

    1.安装:npm install angular-gridster2 --save 2.引入 3.html代码 <div id="fullscreen" style=&quo ...

  4. DTO的理解

    首要的作用,我认为就是减少原生对象的多余参数.包括为了安全,有时候也为了节约流量.例如:密码,你就不能返回到前端.因为不安全. 其次假如说:获取博客列表的时候,也不能返回博客全文吧.顶多就返回标题,i ...

  5. win10启动和安装nacos服务

    https://blog.csdn.net/tbmingzhao/article/details/113276845

  6. python高阶编程(一)

    1.生成器 通过列表⽣成式,我们可以直接创建⼀个列表.但是,受到内存限制,列表容量肯定是有限的.⽽且,创建⼀个包 含100万个元素的列表,不仅占⽤很⼤的存储空间,如果我们仅仅需要访问前⾯⼏个元素,那后 ...

  7. 针对FILES和PATH的操作

    在修改漏洞的时候发现,根据建议都使用NIO包的FILES和PATH来进行文件操作,来保证安全性. import java.nio.file.Files;import java.nio.file.Pat ...

  8. junit单元测试踩过的坑

    1.测试方法不能直接获取到系统初始化的配置信息,需要专门读取 2.单元测试多线程子线程不执行,不会像主线程一样等待子线程退出而退出, 会直接退出. . https://blog.csdn.net/yu ...

  9. Vue 解决先渲染 暂无数据

    // 组件 data(){ return { data:null // 设置默认值为null } } // template <div v-show="data != null&quo ...

  10. c#和JS数据加密(转)

    前台提交按纽 后以赋值后台取值    Base64编解码   C# /* 编码规则 Base64编码的思想是是采用64个基本的ASCII码字符对数据进行重新编码. 它将需要编码的数据拆分成字节数组. ...