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");
    }
}
相关推荐
我叫张小白。12 分钟前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
uzong2 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
q***69773 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
IUGEI4 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
间彧4 小时前
GraalVM Native Image:跨平台能力与编译模式深度解析
后端
间彧4 小时前
GraalVM Native Image 与传统 JVM 内存管理:云原生时代的技术选型指南
后端
r***12384 小时前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
b***74884 小时前
前端GraphQL案例
前端·后端·graphql
LSL666_5 小时前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
q***78375 小时前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端