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");
    }
}
相关推荐
Filotimo_8 分钟前
Spring Boot 整合 JdbcTemplate(持久层)
java·spring boot·后端
半桶水专家16 分钟前
Go 语言时间处理(time 包)详解
开发语言·后端·golang
编程点滴16 分钟前
Go 重试机制终极指南:基于 go-retry 打造可靠容错系统
开发语言·后端·golang
码事漫谈40 分钟前
AI编程规模化实践:从1到100的工程化之道
后端
码事漫谈1 小时前
AI编程:更适合0到1的创意爆发,还是1到100的精雕细琢?
后端
码事漫谈1 小时前
Python与C#:从哲学到细节的全面对比
后端
码事漫谈1 小时前
Python与C++:从哲学到细节的全面对比
后端
喵个咪2 小时前
基于 Go-Kratos 与 MCP 的推荐服务实战指南
后端·深度学习·微服务
没有bug.的程序员2 小时前
JVM 整体架构:一套虚拟机的心脏与血管
java·jvm·spring boot·spring cloud·架构
ZHOUZAIHUI3 小时前
WSL(Ubuntu24.04) 安装PostgreSQL
开发语言·后端·scala