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");
    }
}
相关推荐
IT_陈寒2 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic3 小时前
SwiftUI 手势笔记
前端·后端
金銀銅鐵3 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
飘尘5 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
浏览器工程师7 小时前
AI Agent 接浏览器任务,先别让它一路点到底
前端·后端
行者全栈架构师7 小时前
Maven dependency:tree 的 8 个高级用法
java·后端
Chenyiax7 小时前
从一次请求看懂 OkHttp:架构、调度与连接管理
后端
爱勇宝7 小时前
深扒 Anthropic 1680 位工程师简历:应届生几乎没机会,AI 公司最缺的不是博士
前端·后端·程序员
AskHarries8 小时前
工具失败时怎么办:重试、回滚、人工确认和风险提示
后端·程序员