SpringBoot启动后执行方法的五种实现方式
在 SpringBoot 工程 启动后, 执行方法的五种方式:
1、实现 CommandLineRunner 接口
项目初始化完毕后,才会调用方法,提供服务
@Component
public class StartInit2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner====================");
}
}2、实现 ApplicationRunner 接口
同 CommandLineRunner。只是传参格式不一样。CommandLineRunner:没有任何限制;ApplicationRunner:key-value
@Component
public class StartInit3 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("ApplicationRunner=================");
}
}3、实现 ApplicationListener 接口
项目初始化完毕后,才会调用方法,提供服务。注意监听的事件,通常是 ApplicationStartedEvent 或者 ApplicationReadyEvent,其他的事件可能无法注入 bean。
@Component
public class StartInit4 implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("ApplicationListener================ApplicationStartedEvent");
}
}- 如果监听的是
ApplicationStartedEvent事件,则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之前执行; - 如果监听的是
ApplicationReadyEvent事件,则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之后执行;
顺序:
默认是 ApplicationRunner 先执行,如果双方指定了@Order 则按照 @Order的大小顺序执行,小的先执行。
原理:
- SpringApplication 的run方法会执行afterRefresh方法。
- afterRefresh方法会执行callRunners方法。
- callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法
4、@PostConstruct 注解
在项目初始化过程中,就会调用此方法。如果业务逻辑执行很耗时,可能会导致项目启动失败。
@Component
public class StartInit {
@PostConstruct
public void init() {
System.out.println("@PostConstruct===============================");
}
}5、实现 InitializingBean 接口
项目启动时,调用此方法
@Component
public class StartInit6 implements InitializingBean {
@Override
public void afterPropertiesSet() {
System.out.println("InitializingBean====================");
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
IntelliJ IDEA 2020 安装和常用配置(推荐)
这篇文章主要介绍了IntelliJ IDEA 2020 安装和常用配置(推荐),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-08-08
Java中List.contains(Object object)方法使用
本文主要介绍了Java中List.contains(Object object)方法,使用List.contains(Object object)方法判断ArrayList是否包含一个元素对象,感兴趣的可以了解一下2022-04-04
idea查看properties中文变成unicode码的解决方案
这篇文章主要介绍了idea查看properties中文变成unicode码的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-06-06


最新评论