springboot架构启动挂接点

如果想在springboot启动过程中完成某些工作,可以有如下挂接点:

1、main函数里

这个是最古老,也是最简单的挂接点。适合做些与 Spring 容器无关的前置操作。

2、实现CommandLineRunner类

@Component

@Order(1) // 执行优先级,1 比 2 先执行

public class MyCommandLineRunner implements CommandLineRunner {

@Override

public void run(String... args) throws Exception {

// 启动时执行的逻辑,比如初始化缓存、加载字典数据

System.out.println("CommandLineRunner 执行,命令行参数:" + String.join(",", args));

}

}

3、实现ApplicationRunner类

@Component

@Order(2)

public class MyApplicationRunner implements ApplicationRunner {

@Override

public void run(ApplicationArguments args) throws Exception {

// 获取命名参数(如启动时传入 --name=test)

System.out.println("命名参数 name 的值:" + args.getOptionValues("name"));

// 获取非命名参数

System.out.println("非命名参数:" + args.getNonOptionArgs());

}

}

4、单个bean的初始化

@Component

public class MyBean {

@PostConstruct

public void init() {

// 当前 Bean 初始化后执行,比如初始化 Bean 内部的属性

System.out.println("Bean 初始化后执行 @PostConstruct");

}

}

  1. ApplicationListener(监听启动事件)

@Component

public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

// 实现对应接口即可

}

6.@Configuration注解

一般在注解类里实现初始化bean工作,不做业务初始化。

相关推荐
RFG201211 小时前
20、详解Dubbo框架:消费方如何动态获取服务提供方地址?【微服务架构入门】
java·人工智能·后端·微服务·云原生·架构·dubbo
Tadas-Gao17 小时前
基于规范驱动开发的下一代软件工程范式:从理论到实践
驱动开发·架构·系统架构·大模型·llm·软件工程
御坂10101号18 小时前
从暴力扫图到成本估算:SpiceDB 如何重构 ReBAC 性能引擎
算法·性能优化·架构·database
黄俊懿19 小时前
【架构师从入门到进阶】第一章:架构设计基础——第一节:架构设计的目的
架构·系统架构·架构设计
utmhikari20 小时前
【架构艺术】治理后端稳定性的一些实战经验
java·开发语言·后端·架构·系统架构·稳定性·后端开发
礼拜天没时间.1 天前
Docker与Harbor迁移实战:从入门到生产级完整指南
linux·运维·docker·容器·架构·centos
黄俊懿1 天前
【架构师从入门到进阶】第一章:架构设计基础——第二节:架构设计原则
分布式·后端·中间件·架构
技术传感器1 天前
赋能智慧空间:看本体论如何破解城市更新运营难题
人工智能·深度学习·架构
小冷coding1 天前
【项目】医疗数字化升级:基于Spring生态的合规化微服务架构实践
spring·微服务·架构