说明

  • 场景:在 SpringBoot 应用启动后执行某些操作
  • 以下提供 3 种方式,监听 SpringBoot 应用启动

方案一

ApplicationListener<ApplicationReadyEvent>

1
2
3
4
5
6
7
8
9
10
11
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationEventListener implements ApplicationListener<ApplicationReadyEvent> {

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("Application is now ready and running.");
}
}

方案二

@EventListener & ApplicationReadyEvent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.neo.controller;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class XXX {

@EventListener
public void handleApplicationReadyEvent(ApplicationReadyEvent event) {
System.out.println("Handling application ready event.");
}
}

方案三

CommandLineRunner

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class MyCommandLineRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
// 在这里编写你需要执行的代码
System.out.println("Application started...");
}
}