Spring Boot 初始化运行特定方法

Spring Boot提供了两种 “开机自启动” 的方式,ApplicationRunnerCommandLineRunnerapp

这两种方式的目的是为了知足,在容器启动时like执行某些方法。咱们能够经过实现ApplicationRunner或者CommandLineRunner来实现,他们都是在SpringAppliaction执行以后开始执行的。这个特性能够让咱们自定义一些在容器启动时须要初始化的逻辑ide

 

ApplicationRunner接口spa

官方doc:code

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Orderedblog

当该接口包含在SpringApplication中时执行。多个ApplicationRunner经过Order直接进行排序:排序

/**
 * 初始化类
 */
@Order(1) // @Order注解能够改变执行顺序,越小越先执行
@Component
public class MyApplicationRunner1 implements ApplicationRunner {

    /**
     * 会在服务启动完成后当即执行
     */
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        System.out.println("MyApplicationRunner1----" + arg0);
    }

}
/**
 * 初始化类
 */
@Order(2) 
@Component
public class MyApplicationRunner2 implements ApplicationRunner {

    /**
     * 会在服务启动完成后当即执行
     */
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        System.out.println("MyApplicationRunner2----" + arg0);
    }

}

容器启动后的运行结果:接口

能够看到多个ApplicationRunner执行顺序是按照Order中的值执行的,而且每一个的入参都是同一个ApplicationArguments实例(具体缘由后面分析)ip

 

CommandLineRunner接口源码

两者的官方doc基本同样,区别在于接收的参数不同it

/**
 * 初始化类
 */
@Order(1) // @Order注解能够改变执行顺序,越小越先执行
@Component
public class MyCommandLineRunner1 implements CommandLineRunner {

    /**
     * 会在服务启动完成后当即执行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner1----" + args);
    }

}
/**
 * 初始化类
 */
@Order(2)
@Component
public class MyCommandLineRunner2 implements CommandLineRunner {

    /**
     * 会在服务启动完成后当即执行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner2----" + args);
    }

}

容器启动后的运行结果:

能够看到多个CommandLineRunner的执行效果跟ApplicationRunner如出一辙

 

最后看下源码:

SpringApplication启动时,会执行其run方法中的afterRefresh方法:

在afterRefresh中能够看到这两个接口被执行,而且每一个ApplicationRunner或CommandLineRunner实例都是用的同一个入参:

相关文章
相关标签/搜索