admin管理员组

文章数量:1794759

【SpringBoot】19、SpringBoot中实现启动任务

【SpringBoot】19、SpringBoot中实现启动任务

我们在项目中会用到项目启动任务,即项目在启动的时候需要做的一些事,例如:数据初始化、获取第三方数据等等,那么如何在SpringBoot 中实现启动任务,一起来看看吧

SpringBoot 中提供了两种项目启动方案,CommandLineRunner 和 ApplicationRunner 一、CommandLineRunner

使用 CommandLineRunner ,需要自定义一个类区实现 CommandLineRunner 接口,例如:

import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 项目启动任务类 */ @Component @Order(100) public class StartTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { } }

我们首先使用 @Component 将该类注册成为 Spring 容器中的一个 Bean 然后使用 @Order(100) 标明该启动任务的优先级,值越大,表示优先级越小 实现 CommandLineRunner 接口,并重写 run() 方法,当项目启动时,run() 方法会被执行,run() 方法中的参数有两种传递方式 1、在 IDEA 中传入参数 2、将项目打包,在启动项目时,输入以下命令:

java -jar demo-0.0.1-SNAPSHOT.jar hello world 二、ApplicationRunner

ApplicationRunner 与 CommandLineRunner 的用法基本一致,只是接收的参数不一样,可以接收 key-value 形式的参数,如下:

import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 项目启动任务类 */ @Component @Order(100) public class StartTask implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { } }

关于 run 方法的参数 ApplicationArguments:

1、args.getNonOptionArgs();可以用来获取命令行中的无key参数(和CommandLineRunner一样) 2、args.getOptionNames();可以用来获取所有key/value形式的参数的key 3、args.getOptionValues(key));可以根据key获取key/value 形式的参数的value 4、args.getSourceArgs(); 则表示获取命令行中的所有参数

传参方式: 1、在 IDEA 中传入参数 2、将项目打包,在启动项目时,输入以下命令:

java -jar demo-0.0.1-SNAPSHOT.jar hello world --name=xiaoming

以上就是在 SpringBoot 中实现项目启动任务的两种方式,用法基本一致,主要体现在传参的不同上

如您在阅读中发现不足,欢迎留言!!!

本文标签: SpringBoot