今回はSpringが起動時に呼ばれるメソッドについて調べてみたいと思います。
ApplicationReadyEvent
アプリケーションがリクエストを処理する準備ができていることを示すために、可能な限り遅く発行されたイベントです。
アプリケーションとコマンドラインランナーが呼び出された後に送信されます。
ContextRefreshedEvent
ContextRefreshedEventアノテーションは、springBootアプリケーションの起動時にも実行されますが、ApplicationReadyEventとContextRefreshedEventの違いは次のとおりです。ContextRefreshedEventは、ApplicationReadyEventが初期化されるときに実行されます。したがって、ContextRefreshedEventはApplicationReadyEventの前でも実行されます。
使い方
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(MyApplication.class, args);
}
@EventListener(ContextRefreshedEvent.class)
public void ContextRefreshedEventExecute(){
System.out.println("最初に呼ばれます");
}
@EventListener(ApplicationReadyEvent.class)
public void EventListenerExecute(){
System.out.println("次に呼ばれます。");
}
}
参考
https://spring.pleiades.io/spring-boot/docs/current/reference/html/spring-boot-features.html
