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");
    }
}
相关推荐
有梦不弃1 小时前
模块化单体架构设计方案:DDD + 六边形架构落地实践
后端·架构
happymagic3 小时前
java spring boot做的jar包程序,如何实现自动运行启动
java·运维·服务器·spring boot·jar
江南十四行5 小时前
Spring框架核心(上)——IoC控制反转与DI依赖注入详解
java·后端·spring
IT_陈寒6 小时前
Redis缓存击穿把我坑惨了,原来这样设过期时间才靠谱
前端·人工智能·后端
妙码生花6 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十二):管理员权限检查中间件,AI 随意放行预闯大祸
前端·后端·go
创安电气研究所7 小时前
用 Node.js 将变频器运行数据接入 MQTT
后端
董员外7 小时前
RAG 系统进化论(八):Agentic RAG(智能体式 RAG),从回答问题到完成任务
人工智能·后端·设计模式
大勇前进7 小时前
告别 div 满天飞,HTML5 语义化标签真的有必要用吗?
后端
小满zs7 小时前
Go语言第六章(结构体)
后端·go