Springboot项目启动成功后可通过五种方式继续执行
- 实现CommandLineRunner接口
项目初始化完毕后,才会调用方法,提供服务
@Component
public class StartRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner====================");
}
}- 实现ApplicationRunner接口
同 CommandLineRunner。只是传参格式不一样。CommandLineRunner:没有任何限制;ApplicationRunner:key-value
@Component
public class StartRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("ApplicationRunner=================");
}
}- 实现ApplicationListener接口
项目初始化完毕后,才会调用方法,提供服务。注意监听的事件,通常是 ApplicationStartedEvent 或者 ApplicationReadyEvent,其他的事件可能无法注入 bean。
@Component
public class StartListener 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的大小顺序执行,小的先执行
- @PostConstruct注解
在项目初始化过程中,就会调用此方法。如果业务逻辑执行很耗时,可能会导致项目启动失败。
@Component
public class StartInit {
@PostConstruct
public void init() {
System.out.println("@PostConstruct===============================");
}
}- 实现InitalizingBean接口
项目启动时,调用此方法
@Component
public class StartSet implements InitializingBean {
@Override
public void afterPropertiesSet() {
System.out.println("InitializingBean====================");
}
}到此这篇关于Springboot项目启动成功后可通过五种方式继续执行的文章就介绍到这了,更多相关Springboot启动成功后继续执行内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
@FeignClient path属性路径前缀带路径变量时报错的解决
这篇文章主要介绍了@FeignClient path属性路径前缀带路径变量时报错的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-07-07
JavaWeb开发之Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JC
这篇文章主要介绍了JavaWeb开发之Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架的相关资料,需要的朋友可以参考下2016-12-12
SpringBoot中@Value获取值和@ConfigurationProperties获取值用法及比较
在Spring Boot中,@Value注解是一个非常有用的特性,它允许我们将外部的配置注入到我们的Bean中,@ConfigurationProperties用于将配置文件中的属性绑定到 Java Bean 上,本文介绍了@Value获取值和@ConfigurationProperties获取值用法及比较,需要的朋友可以参考下2024-08-08
解决JavaWeb-file.isDirectory()遇到的坑问题
JavaWeb开发中,使用`file.isDirectory()`判断路径是否为文件夹时,需要特别注意:该方法只能判断已存在的文件夹,若路径不存在,无论其实际是否应为文件夹,均会返回`false`,为了解决这个问题,可以采用正则表达式进行判断,但要求路径字符串的结尾必须添加反斜杠(\)2025-02-02
Spring Data JPA系列QueryByExampleExecutor使用详解
这篇文章主要为大家介绍了Spring Data JPA系列QueryByExampleExecutor使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-09-09


最新评论