阿丹:
在一定的业务场景下,当一个服务进行启动了之后。需要让外界感知、或者需要注册的时候,就涉及到需要触发服务启动后实现的指令方法。
Spring Boot 启动项目后执行特定方法有以下几种常见方式:
-
使用注解 @PostConstruct
- 在任何需要在构造器之后但在初始化完成之前执行逻辑的bean上使用此注解。这是最简单的一种方式,但要注意如果该方法执行时间过长,会阻止其他bean的初始化完成,进而延迟整个应用的启动。
1@Component
2public class StartupBean {
3
4 @PostConstruct
5 public void init() {
6 // 这里编写启动后需要执行的代码
7 }
8}
-
实现 CommandLineRunner 或 ApplicationRunner 接口
- 这两种接口都提供了
run()
方法,会在所有Spring Beans初始化完成后并且应用程序准备好接收请求之前执行。 - CommandLineRunner 是当程序是从命令行启动时有用,适合处理命令行参数。
- ApplicationRunner 与之类似,但不依赖于命令行参数。
- 这两种接口都提供了
1@Component
2public class StartupRunner implements CommandLineRunner, ApplicationRunner {
3
4 @Override
5 public void run(String... args) { // CommandLineRunner
6 // 启动后执行的代码
7 }
8
9 @Override
10 public void run(ApplicationArguments args) { // ApplicationRunner
11 // 启动后执行的代码
12 }
13}
-
实现 ApplicationListener 并监听 ApplicationReadyEvent
- 如果你想在应用完全启动并准备就绪后执行某些操作,可以实现 ApplicationListener 接口并监听 ApplicationReadyEvent。
1@Component
2public class StartupEventListener implements ApplicationListener<ApplicationReadyEvent> {
3
4 @Override
5 public void onApplicationEvent(ApplicationReadyEvent event) {
6 // 应用启动成功后执行的操作
7 }
8}
-
通过 Spring Boot 的事件机制注册监听器
- 可以监听除了 ApplicationReadyEvent 之外的其他Spring Boot生命周期事件,比如 ContextRefreshedEvent 等。
-
使用 @EventListener 注解
- 从Spring Framework 4.2开始,可以通过
@EventListener
注解直接在方法上声明监听某个事件,无需实现 ApplicationListener 接口
- 从Spring Framework 4.2开始,可以通过
1@Component
2public class StartupEventHandler {
3
4 @EventListener
5 public void handleStartup(ApplicationReadyEvent event) {
6 // 应用启动成功后执行的操作
7 }
8}
执行顺序:
- @PostConstruct 注解的方法首先执行。
- 然后是实现了 CommandLineRunner 和 ApplicationRunner 接口的 bean 中的 run 方法,其执行顺序可通过实现 Ordered 接口或使用 @Order 注解来控制。
- 当所有Spring Boot启动过程完成,并发出 ApplicationReadyEvent 时,实现了 ApplicationListener 的 bean 里的对应方法才会执行。