Spring Boot 简明教程
Spring Boot - Runners
Application Runner 和 Command Line Runner 接口允许您在启动 Spring Boot 应用程序后执行代码。您可以在应用程序启动后立即使用这些接口执行任何操作。本章会详细讨论。
Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the application has started. This chapter talks about them in detail.
Application Runner
Application Runner 是一个在启动 Spring Boot 应用程序后用于执行代码的接口。下面给出的示例展示了如何在主类文件上实现 Application Runner 接口。
Application Runner is an interface used to execute the code after the Spring Boot application started. The example given below shows how to implement the Application Runner interface on the main class file.
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 下面的控制台窗口,则会发现 println 语句是在 Tomcat 启动后执行的。以下屏幕截图是否相关?
Now, if you observe the console window below Hello World from Application Runner, the println statement is executed after the Tomcat started. Is the following screenshot relevant?
Command Line Runner
Command Line Runner 是一个接口。它用于在启动 Spring Boot 应用程序后执行代码。下面给出的示例展示了如何在主类文件上实现 Command Line Runner 接口。
Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started. The example given below shows how to implement the Command Line Runner interface on the main class file.
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");
}
}
查看下面 控制台窗口中的“来自 Command Line Runner 的 Hello world”,在 Tomcat 启动后执行 println 语句。
Look at the console window below “Hello world from Command Line Runner” println statement is executed after the Tomcat started.