spring 启动系统任务commandLineRunner

启动系统任务

有一些特殊的任务需要在系统启动时执行,例如配置文件加载、数据库初始化等操作。如果没有使用Spring Boot,这些问题可以在Listener中解决。

Spring Boot对此提供了两种解决方案:CommandLineRunner和ApplicationRunner。CommandLineRunner和ApplicationRunner基本一致,差别主要体现在参数上。

CommandLineRunner

Spring Boot项目在启动时会遍历所有CommandLineRunner的实现类并调用其中的run方法,如果整个系统中有多个CommandLineRunner的实现类,那么可以使用@Order注解对这些实现类的调用顺序进行排序。在一个Spring Boot Web项目中添加两个CommandLineRunner,分别如下:

 MyCommandLineRunner.java

package com.shrimpking.config;

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

import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/5 10:41
 */
@Component
@Order(1)
public class MyCommandLineRunner1 implements CommandLineRunner
{

    @Override
    public void run(String... args) throws Exception
    {
        System.out.println("Runner1>>>" + Arrays.toString(args));
    }
}

MyCommandLineRunner2.java

package com.shrimpking.config;

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

import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/5 10:42
 */
@Component
@Order(2)
public class MyCommandLineRunner2 implements CommandLineRunner
{

    @Override
    public void run(String... args) throws Exception
    {
        System.out.println("Runner2>>>" + Arrays.toString(args));
    }
}

代码解释:

• @Order(1)注解用来描述CommandLineRunner的执行顺序,数字越小越先执行。

• run方法中是调用的核心逻辑,参数是系统启动时传入的参数,即入口类中main方法的参数(在调用SpringApplication.run方法时被传入Spring Boot项目中)。

在系统启动时,配置传入的参数。以IntelliJ IDEA为例,配置方式如下:

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

虾米大王

有你的支持,我会更有动力

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

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

打赏作者

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

抵扣说明:

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

余额充值