前言
在使用SpringBoot的实际过程中,可能会遇到这样的需求:在项目启动完成后需要立即执行一些操作,如加载配置文件,初始化线程池等。在SpringBoot中org.springframework.boot下提供了两个接口来实现其需求:
ApplicationRunner和CommandLineRunner
这两个接口中都提供了一个run方法,在实现接口时进行覆盖,他们会在容器启动完成后自动执行其中的内容。
ApplicationRunner和CommandLineRunner的区别
两者作用是一样的,区别在与前者run方法参数为ApplicationArguments****对象,是对原始参数做了封装,而后者为原始String数组。注:这些参数都是传递给main方法的参数。
package org.springframework.boot;
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
package org.springframework.boot;
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
执行顺序
在SpringBoot中,不止一个Bean可以实现ApplicationRunner或CommandLineRunner,为了能控制其run方法的执行顺序,支持使用@Order注解来进行执行排序。注:在均实现ApplicationRunner和CommandLineRunner时,ApplicationRunner的run方法会先执行。
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 服务启动后立即执行
* @author CK
*/
@Component
@Order(1)
public class StartRun implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner执行!");
}
}