您有多种选择:
使用 CommandLineRunner 或 ApplicationRunner 作为 Bean 定义:
Spring Boot 在应用程序启动过程结束时执行这些操作。在大多数情况下,CommandLineRunner 将完成这项工作。以下是使用 Java 8 实现 CommandLineRunner 的示例:
@Bean
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World");
}
请注意,args 是 String 参数数组。您还可以提供此接口的实现并将其定义为 Spring 组件:
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Hello World");
}
}
如果您需要更好的参数管理,可以使用ApplicationRunner。 ApplicationRunner 采用具有增强的参数管理选项的ApplicationArguments 实例。
您还可以使用 Spring 的 @Order 注释订购 CommandLineRunner 和 ApplicationRunner bean:
@Bean
@Order(1)
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World, Order 1");
}
@Bean
@Order(2)
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World, Order 2");
}
使用 Spring Boot 的 ContextRefreshedEvent:
Spring Boot 在启动时会发布几个事件。这些事件表明应用程序启动过程中某个阶段的完成。你可以收听ContextRefreshedEvent并执行自定义代码:
@EventListener(ContextRefreshedEvent.class)
public void execute() {
if(alreadyDone) {
return;
}
System.out.println("hello world");
}
ContextRefreshedEvent 被多次发布。因此,请确保检查代码执行是否已经完成。