Skip to content
欢迎扫码关注公众号

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 启动过程中的一个较晚阶段,确保所有初始化步骤都已完成。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.