来源:自学PHP网 时间:2020-09-27 14:17 作者:小飞侠 阅读:次
[导读] SpringBoot中实现启动任务的实现步骤...
今天带来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 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一样) 传参方式: 1、在 IDEA 中传入参数
|
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com