SpringBoot项目启动时的初始化操作

SpringBoot项目启动时的初始化操作包括:

类的静态代码、类的构造函数、@Autowired装载变量、@PostConstruct修饰方法、实现ApplicationRunner接口、实现CommandLineRunner接口,其执行的先后次序为:

static > constructer > @Autowired > @PostConstruct > ApplicationRunner > CommandLineRunner

这里主要介绍实现ApplicationRunner接口、CommandLineRunner接口的方式进行初始化操作

实现 ApplicationRunner 接口

java 复制代码
@Component
@Order(1) /// 多个类实现该接口的优先级
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("order1:MyApplicationRunner");
 
    }
}

实现 CommandLineRunner 接口

java 复制代码
@Component
@Order(2)  /// 多个类实现该接口的优先级
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("order2:MyCommandLineRunner");
    }
}
相关推荐
杨运交3 分钟前
[069][公共模块]Spring Boot 全局异常处理与参数校验实战(下):校验异常精细化处理与 WebFlux 适配
java·spring boot·后端
行者-全栈开发16 分钟前
Spring Boot + FFmpeg 视频批量处理实战:压缩、HLS切片与异步任务引擎
spring boot·ffmpeg·异步处理·视频压缩·hls切片·批量任务·redis队列
Andya_net30 分钟前
Spring Boot | 条件注解完全指南:从 @Conditional 到 @ConditionalOnExpression 的原理、实践与避坑
spring boot·后端·python
ly768944 分钟前
Spring 中的 @Configuration 与 @Component 差异:为何代理时机决定 Bean 生命周期行为
java·后端·spring·注解·代理·bean生命周期
明月_清风1 小时前
字符串匹配四大经典算法:BF、RK、BM、KMP 到底有什么区别?
后端·算法
卷无止境1 小时前
测试全绿,功能能跑,代码却烂到没法上线:AI编程助手留下的十个坑
后端·python
明月_清风1 小时前
多模式字符串匹配:Trie 与 AC 自动机
后端·算法
小荷才露尖尖角,早有蜻蜓立上头1 小时前
class java.util.LinkedHashMap cannot be cast to xxx
java·spring boot
嘻哈baby2 小时前
不用 LangChain,从 0 写一个 Ollama 本地 RAG
后端
MZA6662 小时前
Spring Boot 实战:基于自定义注解 + AOP 实现 Kafka 消息无侵入异步上送
java·spring boot·kafka