Spring Boot:理解CommandLineRunner和ApplicationRunner

 1.前言

    在实际开发中,有些操作需要在项目启动的时候初始化,例如线程池、提前加载好加密证书等。CommandLineRunner和ApplicationRunner中的run()方法可以实现。

    CommandLineRunner和ApplicationRunner的作用基本相同的,区别在于CommandLineRunner接口的run()方法接收String数组作为参数,即是最原始的参数;ApplicationRunner接口的run()方法接收ApplicationArguments对象作为参数,是对原始参数的封装。

    如果注入了两个实现CommandLineRunner或ApplicationRunner的Bean,可以在类上用@Order注解按顺序执行 

2.配置启动参数

Spring Boot:理解CommandLineRunner和ApplicationRunner配置启动参数(可选) 

3.CommandLineRunner

package cn.duckweed.runner.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author yyx
 * @Date 2021/10/23 18:11
 */
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyCommandLineRunner.class);

    @Override
    public void run(String... args) throws Exception {
        LOGGER.info("Application started with arguments:" + Arrays.toString(args));
    }
}

4.ApplicationRunner

package cn.duckweed.runner.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author yyx
 * @Date 2021/10/23 18:36
 */
@Component
public class MyApplicationRunner implements ApplicationRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyApplicationRunner.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        LOGGER.info("Application started with arguments:" + Arrays.toString(args.getSourceArgs()));
    }
}
上一篇:问题7.2 用si和di实现将字符串‘welcome to masm!’复制到它后面的数据区中


下一篇:8086汇编 杂项案例