将@ConditionalOnProperty与多个@PropertySource一起使用

时间:2019-01-09 10:34:40

标签: spring-boot

我有一些带有@ConditionalOnProperty的bean,该属性取自某些@PropertySource。但是我有多个@PropertySources。仅在其中之一中,将定义条件的给定属性。但是令我惊讶的是,@ConditionalOnProperty注释会查询每个属性源。而且由于属性并非在每个属性源中都存在,因此PropertyResolver会将Bean标记为非数学。

我想拥有的是接口,具有实际的实现和无操作实现,并控制将使用哪种实现。我不想使用配置文件来控制它,但是配置文件是基于条件的,因此应该有一种方法。所以对我来说,发生的事情是我无视任何设置而没有实现。当然,我可以添加matchIfMissing,然后无论设置如何,我都会被遗弃。

注释为:

@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")

,并且在属性文件中是

feature.enabled=true

这是怎么了?但是,实际上不可能,如果我使用@Conditional ...,我只需要使用一个属性源,对吗?

更新: 具有以下bean定义,我具有上述行为:没有注册任何bean,因为feature.enabled中未定义application.properties。添加matchIfMissing=true无济于事,因为将始终添加带有此参数的bean,因为它(始终)不存在于application.properties中。添加@ConditionalOnMissingBean也没有帮助我。我在feature.enabled中将another.properties设置为true,但是FeatureImpl被否决了,因为存在属性source,其中feature.enabled不是true。令人惊讶的是,当时没有使用@ConditionalOnMissingBean注释的FeatureNoOp。不知道为什么。

@Service
@Slf4j
@ConditionalOnProperty(name = "feature.enabled", havingValue = "false")
public class FeatureNoOp implements Feature {

vs

@Service
@Slf4j
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureImpl implements Feature {

配置如下:

@Configuration
@PropertySource("classpath:application.properties")
public class Config {

    //...


    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Configuration
    @PropertySource("classpath:another.properties")
    @Profile("war-deployment")
    public static class WarDeploymentConfig {
        //...
    }
}

1 个答案:

答案 0 :(得分:0)

真正的原因是,正如M.Deinum正确建议的(谢谢!),在@PropertySource批注中。

对于application.properties,我拥有@PropertySource,此外,我还有一些类似于下面的配置类,只是为了基于活动配置文件引入另一个属性源:

@Configuration
@PropertySource("classpath:profile-related-properties.properties")
@Profile("some-profile")
public static class SomeProfileConfig {}

即使这提供了一些明确的说法,说明正在使用什么,它显然也存在一些问题。我更改了代码,以免我“反复”声明对application.properties的使用并重命名了文件/配置文件,以便可以使用另一个自动发现的属性模式:application- {profile_name} .properties。更改之后,一切都会按预期进行。