第三章:SpringBoot2.3.0 ApplicationRunner或CommandLineRunner

一)ApplicationRunner或CommandLineRunner简介

当SpringBoot启动之后,如需执行一些特定的代码,这两个接口以相同的方式工作,并提供一个单一的run方法,该方法在SpringApplication.run(…​)完成之前就被调用

比如说,预先加载一些配置,注册一些bean等等。

 

二)CommandLineRunner

该接口只提供了run方法,并且入参是String类型。

@Component:此注解把该类声明成一个bean。

@Order:当有多个类继承了CommandLineRunner接口,可指定执行的顺序。

package com.oysept.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=1)
public class FirstCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner, 1111" + args);
    }
}

 

三)ApplicationRunner

该接口只提供了run方法,并且入参是ApplicationArguments对象类型。

@Component:此注解把该类声明成一个bean。

@Order:当有多个类继承了CommandLineRunner接口,可指定执行的顺序。

package com.oysept.config;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=2)
public class FirstApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner, 2222" + args);
    }
}

 

四)区别

1、两个接口run方法,入参不同,ApplicationRunner.run()入参是ApplicationArguments对象类型,CommandLineRunner.run入参是String类型。

2、ApplicationArguments参数已包含String的参数。也就是说,当只需要String类型入参时,继承CommandLineRunner即可。当入参需多样化时,可继承ApplicationRunner接口。

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值