如果需要在 SpringApplication 启动后执行一些特殊的代码,你可以实现ApplicationRunner 或 CommandLineRunner 接口,这两个接口工作方式相同,都只提供单一的 run 方法,该方法仅在 SpringApplication.run(…) 完成之前调用。
CommandLineRunner 接口能够访问string数组类型的应用参数,而 ApplicationRunner 使用 ApplicationArguments 接口:
package com.example.runner;
import org.springframework.boot.CommandLineRunner;
public class TestRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("start run CommandLineRunner");
}
}