首页 > 技术文章 > CommandLineRunner 系统启动任务

antaia11 2021-08-02 23:00 原文

CommandLineRunner 系统启动任务

1.CommandLineRunner

MyCommandLineRunner.java

package com.zhuantai.commandlinerunner;

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

import java.util.Arrays;

/**
 * 系统启动任务
 * @author ANTIA1
 * @date 2021/7/8 16:05
 */
@Component
@Order(100)//指定优先级,数字越小优先级越大
public class MyCommandLineRunner implements CommandLineRunner {
    //当系统启动时,run方法会被触发,方法参数就是 main 方法所传入的参数
    @Override
    public void run(String... args) throws Exception {
        System.out.println("args=" + Arrays.toString(args));

    }
}

测试:

image-20210708161144477

运行结果:

image-20210708161210201

测试2:

D:\Project\spring-boot-demos\commandlinerunner\target>java -jar commandlinerunner-0.0.1-SNAPSHOT.jar 朱安泰 张三 李四

运行结果:

image-20210708161342609

2.ApplicationRunner

package com.zhuantai.commandlinerunner;

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

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author ANTIA1
 * @date 2021/7/8 19:22
 */
@Component
@Order(90)
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {

        //获取没有key的参数,获取到的值和commandLineRunner一致
        List<String> nonOptionArgs = args.getNonOptionArgs();
        System.out.println("nonOptionArgs = " + nonOptionArgs);

        //获取键值对参数
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            System.out.println(optionName+" = " + args.getOptionValues(optionName));
        }

        //获取命令行中的所有参数
        String[] sourceArgs = args.getSourceArgs();
        System.out.println("sourceArgs = " + Arrays.toString(sourceArgs));
    }
}

运行结果:

image-20210708193037510

推荐阅读