SpringBoot定义系统启动任务的两种方式

目的: 平常开发中有可能需要实现在项目启动后执行的自定义的一些功能,实现自定义初始化任务。

一、CommandLineRunner

示例代码如下:

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

/**
 * @author qinxun
 * @date 2023-06-16
 * @Descripion: CommandLineRunner方式
 */
@Component
@Order(1)
public class MyCommandLine1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // 项目启动后会执行 我们可以在这里执行自定义的一些处理
        System.out.println("MyCommandLine1运行");
    }
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author qinxun
 * @date 2023-06-16
 * @Descripion: CommandLineRunner方式
 */
@Component
@Order(2)
public class MyCommandLine2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLine2运行");
    }
}

@Component 注解将这个类注入到Spring容器中,接受Spring容器的管理。

@Order注解,表示启动任务的执行优先级,比如有多个类都实现CommandLineRunner,这个时候就可以加上这个注解设置执行的优先级,数字越小,优先级越大,越先执行。

run方法中写启动任务的逻辑,当项目启动时,run方法会被执行。run方法的参数,来自项目的启动参数。

 我们启动项目,在控制台上可以看到在这个方法打印的数据。

 

二、ApplicationRunner

 示例代码如下:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author qinxun
 * @date 2023-06-16
 * @Descripion: ApplicationRunner方式
 */
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 项目启动后会执行 我们可以在这里执行自定义的一些处理
        System.out.println("MyApplicationRunner运行");
    }
}

我们启动项目,在控制台上可以看到在run方法打印的数据。

 三、区别

CommandLineRunner的参数是String...args,传递的是字符串,run方法里直接获取传递的字符串。

ApplicationRunner的参数是ApplicationArguments,对参数进行了封装。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qinxun2008081

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值