首页 > 解决方案 > 在 WebServer 启动前触发 ApplicationListener

问题描述

我有一个短暂的过程来将一个简单的文件从类路径读取到内存中,我选择ApplicationListener<ApplicationReadyEvent>让 spring 触发一个任务:

@Component
@Priority(1)
class MyLoader implements ApplicationListener<ApplicationReadyEvent> {

  @Override
  public void onApplicationEvent(ApplicationReadyEvent event) {
    doStuff();
  }

}

我意识到我在这个应用程序中提供的 HTTP 请求并不依赖于内存中的数据。如何MyLoader在 Web 服务器准备好服务请求之前强制执行类?我不知道如何定义这种依赖关系?

标签: javaspringspring-boot

解决方案


You should listen for an event before the ApplicationReadyEvent, because it is the final one, marking that the application is ready to serve requests.

For example, you can listen to ApplicationStartingEvent. See a list of the available ApplicationEvents here.


推荐阅读