【问题标题】:Spring Boot @ConditionalOnProperty not resolving propertySpring Boot @ConditionalOnProperty 不解析属性
【发布时间】:2021-04-19 08:40:54
【问题描述】:

在我的 Spring Boot 项目 (SB v2.4.4) 中,我尝试使用 @ConditionalOnProperty 有条件地启用配置类:

@ConditionalOnProperty(
        value = "feature1.enabled",
        havingValue = "true",
        matchIfMissing = false
)
@Configuration
public class NewConfig {
    ...
}

属性feature1.enabled 在使用第二个配置类加载的features.properties 文件中声明:

@Configuration
@PropertySource("classpath:features.properties")
public class FeaturesConfig {
}

features.properties 中声明的属性已正确加载,但 @ConditionalOnProperty 似乎无法解析 feature1.enabled

我还尝试用 @DependsOn("featuresConfig") 注释 NewConfig 类,但没有任何变化。

似乎唯一可行的方法是将feature1.enabled 移动到application.properties

那么为什么这不起作用?我的配置有什么问题?

【问题讨论】:

  • 因为@PropertySource 的属性是在检查了所有@Conditionals 之后才加载的。所以把它放在一个没有作为 Spring Boot 的一部分加载的属性文件中是行不通的。您需要使用正确的命令行参数将其作为附加属性文件添加到 Spring Boot。

标签: java spring spring-boot configuration


【解决方案1】:

正如 M.Denium 在他的评论中所建议的,我解决了在应用程序启动时添加此命令行参数的问题:

-Dspring.config.additional-location=classpath:/features.properties

添加features.properties 文件作为我的应用程序的附加配置位置,修复了@ConditionalOnProperty 中的属性解析问题。

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 2021-09-02
    • 2023-03-04
    • 2022-01-16
    • 2021-05-16
    • 2018-07-20
    • 2021-03-08
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多