【工作笔记】CommandLineRunner接口和ApplicationRunner接口

作用

CommandLineRunner 接口和 ApplicationRunner 接口是在容器启动成功后的最后一步回调,可以在项目成功启动后做一些检查工作或执行一些任务。如果多个检查工作需要按照一定的顺序去执行,那么就需要在实体类上使用一个 @Order 注解(或者实现 Order 接口)来表明顺序(order 值越小越先执行,默认 2147483647,最后执行)

  • CommandLineRunner 用法
package com.just;

import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class StartCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(JSONObject.toJSONString(args)); //["program.start.success!!!"]
    }

}

  • ApplicationRunner 用法
package com.just;

import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class StartApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(JSONObject.toJSONString(args)); //["program.start.success!!!"]
    }
}

原理

源码

private void callRunners(ApplicationContext context, ApplicationArguments args) {
	List<Object> runners = new ArrayList<>();
	// 获取所有实现ApplicationRunner接口的类
	runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
	// 获取所有实现CommandLineRunner接口的类
	runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
	// 按照order排序
	AnnotationAwareOrderComparator.sort(runners);
	for (Object runner : new LinkedHashSet<>(runners)) {
		// 执行排完序的方法
		if (runner instanceof ApplicationRunner) {
			callRunner((ApplicationRunner) runner, args);
		}
		if (runner instanceof CommandLineRunner) {
			callRunner((CommandLineRunner) runner, args);
		}
	}
}
package org.springframework.boot;

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

// 获取启动参数的接口
public interface ApplicationArguments {

	String[] getSourceArgs();

	Set<String> getOptionNames();

	boolean containsOption(String name);

	List<String> getOptionValues(String name);

	List<String> getNonOptionArgs();
}

添加项目启动参数

  • 方法一:如果使用 idea。(1)点击 Edit Configurations 窗口;(2)Program arguments 即 main 方法的 args 参数传入
  • 方法二:直接在项目启动参数添加命令行
    –program.start.success!!!

关于 order 接口

public interface Ordered {
	int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
	int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
	int getOrder();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值