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启动成功后继续执行内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringCloud Netflix Ribbon源码解析(推荐)
这篇文章主要介绍了SpringCloud Netflix Ribbon源码解析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-03-03如何用JAVA判断当前时间是否为节假日、周末、工作日及调休日(不报错:IOException!)
最近公司有个业务需要判断工作日,但是每年的节假日不一样,下面这篇文章主要给大家介绍了关于如何用JAVA判断当前时间是否为节假日、周末、工作日及调休日的相关资料,且不报错:IOException!,需要的朋友可以参考下2023-12-12java计算给定字符串中出现次数最多的字母和该字母出现次数的方法
这篇文章主要介绍了java计算给定字符串中出现次数最多的字母和该字母出现次数的方法,涉及java字符串的遍历、转换及运算相关操作技巧,需要的朋友可以参考下2017-02-02SpringMVC的处理器拦截器HandlerInterceptor详解
这篇文章主要介绍了SpringMVC的处理器拦截器HandlerInterceptor详解,SpringWebMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于处理器进行预处理和后处理,需要的朋友可以参考下2024-01-01
最新评论