Spring Boot - Runners
Application Runner 和 Command Line Runner 接口允许您在 Spring Boot 应用程序启动后执行代码。 您可以使用这些接口在应用程序启动后立即执行任何操作。 本章将详细讨论它们。
Application Runner
Application Runner 是一个接口,用于在 Spring Boot 应用程序启动后执行代码。 下面给出的示例显示了如何在 main 主类文件上实现 Application Runner 接口。
package com.tutorialspoint.demo; 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"); } }
现在,如果您观察 Hello World from Application Runner 下面的控制台窗口,则在 Tomcat 启动后执行 println 语句。 以下屏幕截图是否相关?

Command Line Runner
Command Line Runner 是一个界面。 它用于在 Spring Boot 应用程序启动后执行代码。 下面给出的示例显示了如何在 main 主类文件上实现 Command Line Runner 接口。
package com.tutorialspoint.demo; 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"); } }
看下面的控制台窗口 "Hello world from Command Line Runner", println 语句是在 Tomcat 启动后执行的。
