应用程序运行器(Runner)和命令行Runner接口允许在SpringBoot应用程序启动后执行代码,可以使用这些接口在应用程序启动后立即执行一些操作。

概述

在做web项目开发中,尤其是在企业级应用开发过程中,往往会在项目启动的时候加载一些数据,在 springBoot 应用中,我们可以在程序启动之前执行任何任务。 为了达到这个目的,我们需要使用 CommandLineRunner 或 ApplicationRunner 接口创建 bean,springBoot 会自动监测到它们。这两个接口都有一个 run() 方法,在实现接口时需要覆盖该方法,并使用 @Component 使其成为 bean。 CommandLineRunner 和 ApplicationRunner 接口的 run() 方法在 SpringApplication 完成启动时执行。启动完成之后,应用开始运行。CommandLineRunner 和 ApplicationRunner 的作用是相同的,不同之处在于 CommandLineRunner接口的 run() 方法接收String数组作为参数,而 ApplicationRunner 接口的 run() 方法接收 ApplicationArguments 对象作为参数。当程序启动时,我们传给 main() 方法的参数可以被实现 CommandLineRunner 和 ApplicationRunner 接口的类的 run() 方法访问。 我们可以创建多个实现 CommandLineRunner 和 ApplicationRunner 接口的类。为了使他们按一定顺序执行,可以使用 @Order 或实现 Ordered 接口。

运行器

应用程序运行器

ApplicationRunner和CommandLineRunner的作用相同。在SpringApplication.run()完成spring boot启动之前,ApplicationRunner的run()方法会被执行

import org.springframework.boot.ApplicationArguments;

import org.springframework.boot.ApplicationRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication implements ApplicationRunner {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

@Override

public void run(ApplicationArguments arg0) throws Exception {

System.out.println("Hello World from Application Runner");

}

}

命令行运行器

CommandLineRunner是个接口,有一个run()方法。为了使用CommandLineRunner我们需要创建一个类实现该接口并覆盖run()方法。使用@Component注解实现类。当SpringApplication.run()启动spring boot程序时,启动完成之前,CommandLineRunner.run()会被执行。CommandLineRunner的run()方法接收启动服务时传过来的参数。

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication implements CommandLineRunner {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

@Override

public void run(String... arg0) throws Exception {

System.out.println("Hello world from Command Line Runner");

}

}