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

Spring Boot库如何读取主项目application.properties中的配置?

问题原因

你现在的问题出在手动new出来的LoggingProperties实例没有被Spring容器管理,所以@ConfigurationProperties注解的配置绑定逻辑根本没触发,自然读不到主项目application.properties里的配置值。

解决方法

有两种常见的修正方式,选一种就行:

方式1:给LoggingProperties添加@Component注解

让LoggingProperties本身成为Spring Bean,这样Spring会自动处理它的配置绑定:

@Component
@ConfigurationProperties(prefix = "logging")
public class LoggingProperties {

    private boolean extendedLoggingEnabled;

    public boolean isExtendedLoggingEnabled() {
        return extendedLoggingEnabled;
    }

    public void setExtendedLoggingEnabled(boolean extendedLoggingEnabled) {
        this.extendedLoggingEnabled = extendedLoggingEnabled;
    }
}

然后修改LibraryConfig,通过参数注入的方式获取Spring管理的LoggingProperties实例:

@Configuration
public class LibraryConfig {

    @Bean
    public LoggingRequestInterceptor loggingRequestInterceptor(LoggingProperties properties) {
        return new LoggingRequestInterceptor(properties);
    }

}

方式2:在LibraryConfig中定义LoggingProperties的Bean

如果不想给LoggingProperties加@Component,可以在配置类里显式定义它的Bean,并加上@ConfigurationProperties注解,同时开启@EnableConfigurationProperties:

@Configuration
@EnableConfigurationProperties
public class LibraryConfig {

    @Bean
    @ConfigurationProperties(prefix = "logging")
    public LoggingProperties loggingProperties() {
        return new LoggingProperties();
    }

    @Bean
    public LoggingRequestInterceptor loggingRequestInterceptor(LoggingProperties properties) {
        return new LoggingRequestInterceptor(properties);
    }

}
原理说明

只有当LoggingProperties是Spring容器中的Bean时,Spring的ConfigurationPropertiesBindingPostProcessor才会扫描到它,将application.properties中以logging为前缀的配置值,自动映射到对应的属性上(比如logging.extended-logging-enabled对应extendedLoggingEnabled字段)。你之前手动new的实例不在Spring管理范围内,所以这个绑定过程不会执行。

内容的提问来源于stack exchange,提问作者Luis González

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:10:33