当我们需要让 Spring Boot 在启动第一时间就去执行一段代码,可以通过添加事件监听实现,具体如下:
添加事件
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;public class MyEvent implements ApplicationListener<ApplicationStartingEvent> {@Overridepublic void onApplicationEvent(ApplicationStartingEvent event) {// todo}
}
添加监听
@SpringBootApplication
public class StartApplication {public static void main(String[] args) {SpringApplication app = new SpringApplication(StartApplication.class);app.addListeners(new MyEvent());app.run(args);}
}