You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Spring Boot构建属性作为常规Spring属性用于Logback配置?

解决方案

要让logback-spring.xml能通过springProperty调用build-info.properties中的属性,核心是把构建属性注册到Spring应用上下文的环境属性源中——默认的BuildProperties Bean不会自动完成这一步。以下是具体实现:

1. 实现环境属性处理器

创建一个EnvironmentPostProcessor实现类,手动读取build-info.properties并将其添加到Spring环境属性源:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.util.Properties;

public class BuildInfoEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String BUILD_INFO_PATH = "/META-INF/build-info.properties";
    private static final String PROPERTY_SOURCE_NAME = "buildInfoProperties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        try {
            ClassPathResource resource = new ClassPathResource(BUILD_INFO_PATH);
            if (resource.exists()) {
                Properties properties = new Properties();
                properties.load(resource.getInputStream());
                // 将构建属性添加到环境属性源末尾,避免覆盖已有属性
                environment.getPropertySources().addLast(new PropertiesPropertySource(PROPERTY_SOURCE_NAME, properties));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 注册处理器

在src/main/resources/META-INF/spring.factories文件中添加配置,让Spring Boot识别这个处理器:

org.springframework.boot.env.EnvironmentPostProcessor=com.yourpackage.BuildInfoEnvironmentPostProcessor

注意替换com.yourpackage为你实际的类包路径。

3. 验证Logback配置

你的logback-spring.xml配置无需修改,保持原有写法即可:

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <springProperty scope="context" name="application" source="build.name"/>
  <springProperty scope="context" name="version" source="build.version"/>
</configuration>

原理说明

EnvironmentPostProcessor会在Spring应用上下文初始化前处理环境属性,确保Logback加载配置时,build.name、build.version等属性已经存在于环境属性源中,这样springProperty就能正常读取到值。

内容的提问来源于stack exchange,提问作者Oliver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:13:27