Spring Boot学习(六):ApplicationRunner和CommandLineRunner

前言

在开发中,有时候我们需要在容器启动的时候做一些初始化或者其他的操作。这时候,我们在Spring Boot项目中应该怎么做呢?


callRunners方法

我们在上一篇分析Spring Boot的run()方法时候,在创建并刷新了ApplicationContext之后会调用一个callRunners方法

如下

callRunners(context, applicationArguments);


private void callRunners(ApplicationContext context, ApplicationArguments args) {
		List<Object> runners = new ArrayList<>();
		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
		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);
			}
		}
	}


//ApplicationRunner 的callRunner方法

private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
		try {
			(runner).run(args);
		}
		catch (Exception ex) {
			throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
		}
	}

从代码中,我们可以看到,如果有bean的类型是ApplicationRunner或者CommandLineRunner,那么就会执行该bean下的run方法。

以下为ApplicationRunner和CommandLineRunner的源码,我们可以看到两个接口,都只有一个run方法而已

public interface ApplicationRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming application arguments
	 * @throws Exception on error
	 */
	void run(ApplicationArguments args) throws Exception;

}


public interface CommandLineRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}

所以,我们如果想在上下文启动成功之后,做一些操作的话,只需要实现ApplicationRunner 或者CommandLineRunner 接口就可以了。这两个接口的区别知识run方法的参数不一样,ApplicationRunner 的run方法参数为ApplicationArguments 对象,而CommandLineRunner 的run方法参数为字符串。

注意:String…是java5新加入的功能,表示的是一个可变长度的参数列表。其语法就是类型后跟…,表示此处接受的参数为0到多个类型的参数


测试

以下是我做的一个小测试

@Component
public class MyTestApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("进行初始化操作");
    }
}

结果
在这里插入图片描述

2020-06-06 16:22:56.754 INFO 175548 — [ main] com.example.demo.DemoApplication : Started DemoApplication in 79.004 seconds (JVM running for 88.532)
进行初始化操作

可以看到我们在run方法中的代码是在Application启动完成后再运行的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值