Spring Boot 应用启动时打印配置类信息

因为项目中有些配置是在环境变量中指定的,所以想在启动时打印一下实际的配置参数,以方便确认配置是否正确。

下面是查到的比较优雅的写法:通过监听 ApplicationReadyEvent 事件,在事件触发时打印配置参数

java 复制代码
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class MyApplicationListener {

    private final MyProperties myProperties;

    @EventListener(ApplicationReadyEvent.class)
    public void handleApplicationReadyEvent() {
        // 打印配置参数
        log.info("我的配置 {}", myProperties);
    }
}

其中 MyProperties 配置类上加了 Lombok 的 @Data 注解,会自动生成 toString 方法。

ApplicationReadyEvent 事件在 ApplicationContext 被初始化和刷新后,且应用程序已经准备好处理请求时触发。这是 Spring Boot 启动过程中的一个较晚阶段,确保所有初始化步骤都已完成。

相关推荐
吴生439630 分钟前
数据库ALGORITHM = INSTANT 特性研究过程
后端
程序猿chen1 小时前
JVM考古现场(十九):量子封神·用鸿蒙编译器重铸天道法则
java·jvm·git·后端·程序人生·java-ee·restful
Chandler241 小时前
Go:接口
开发语言·后端·golang
ErizJ1 小时前
Golang|Channel 相关用法理解
开发语言·后端·golang
automan021 小时前
golang 在windows 系统的交叉编译
开发语言·后端·golang
Pandaconda1 小时前
【新人系列】Golang 入门(十三):结构体 - 下
后端·golang·go·方法·结构体·后端开发·值传递
我是谁的程序员1 小时前
Flutter iOS真机调试报错弹窗:不受信任的开发者
后端
蓝宝石Kaze1 小时前
使用 Viper 读取配置文件
后端
aiopencode1 小时前
Flutter 开发指南:安卓真机、虚拟机调试及 VS Code 开发环境搭建
后端
开心猴爷1 小时前
M1搭建flutter环境+真机调试demo
后端