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启动成功后继续执行内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java IText异常NoClassDefFoundError: org/bouncycastle
在使用Java进行PDF文档操作时,iText是一个非常强大的库,然而,在实际开发过程中,可能会遇到一些异常情况,其中之一就是NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable,本文将探讨这个错误的原因及其解决方案,需要的朋友可以参考下2025-02-02


最新评论