springboot添加启动事件监听

当我们需要在 springboot 启动时做的第一件事,可以通过添加事件监听实现,具体如下:

添加事件

import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;

public class MyEvent implements ApplicationListener<ApplicationStartingEvent> {

  @Override
  public 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);
  }
}
posted @ 2023-08-20 16:49  这个杀手冷死了  阅读(12)  评论(0编辑  收藏  举报