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");
    }
}
相关推荐
用户574385305111 小时前
第 2 章:裸写 Query(原生驱动)
后端
用户574385305111 小时前
第 8 章:Service 层的诞生(硬编码版)
后端
用户574385305111 小时前
第 3 章:引入 Knex + Schema 自动加载
后端
aiks_yuan1 小时前
Spring AI MCP Server 怎么接入 Claude Code:Spring Boot 用 @McpTool 暴露接口(Spring AI 2.0.2 实测)
spring boot
flash俊杰1 小时前
合并式恢复的事务边界:幂等跳过、外键顺序与向量重建标记
后端
学长毕设1 小时前
基于springboot的实验室设备管理系统
java·spring boot·后端
学长毕设2 小时前
基于springboot的社区养老监护系统的设计与实现
java·spring boot·后端
会编程的吕洞宾2 小时前
RAG检索质量怎么评估?3个指标+LLM裁判实战
java·开发语言·人工智能·后端
wno7042 小时前
Springboot国际化信息(i18n)解析
java·spring boot·后端