22、SpringBoot Runner

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

乔欣Bridgette

概述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独泪了无痕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值