可以通过实现 Spring 的接口 org.springframework.boot.ApplicationRunner 或 org.springframework.boot.CommandLineRunner 来在 web 容器启动之前执行一些操作。这些接口的实现类会在 Spring Boot 应用启动时被自动运行。
ApplicationRunner 的 run() 方法会在 Spring 应用启动完成后被调用,而 CommandLineRunner 的 run(String... args) 方法会在 Spring 应用启动时被调用,这两个接口的返回值类型都是 void 。
例如,以下代码实现了一个 CommandLineRunner 接口:
@
Componentpublic class MyCommandLineRunner implements CommandLineRunner {
@
Override public void run(String... args) throws Exception {
System.out.println("执行 MyCommandLineRunner");
}
}
当 Spring Boot 应用启动时,MyCommandLineRunner 中的 run() 方法会被调用,并输出 执行 MyCommandLineRunner 。