gpt4 book ai didi

java - Springboot yaml配置不读取 boolean 值

转载 作者:行者123 更新时间:2023-12-01 22:40:43 24 4
gpt4 key购买 nike

我是 Springboot 新手。这就是我要解决的问题。我有一个具有以下属性的 application.yml 文件:

kinesis:
streaming:
client:
featuretoggle:
kinesisSenderFeature: true

我尝试使用以下代码访问 KinesisSenderFeature 的值:

@Value("${kinesis.streaming.client.featuretoggle.kinesisSenderFeature}")
private boolean featureToggle;

以及

@Value("${kinesis.streaming.client.featuretoggle.kinesisSenderFeature}")
private Boolean featureToggle;

PropertySourcesPlaceholderConfigurer bean 定义为:

 @Bean
@Primary
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application.yml"));
propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
return propertySourcesPlaceholderConfigurer;
}

当我尝试构建时,ApplicaitonContext 无法加载并出现以下错误:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rabbitMessageConsumer': Unsatisfied dependency expressed through field 'featureToggle'; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [${kinesis.streaming.client.featuretoggle.kinesisSenderFeature}]

我觉得奇怪的是,它试图将字符串:[${kinesis.streaming.client.featuretoggle.kinesisSenderFeature}]转换为 boolean 值,我相信 - 没有读取yaml 文件中的属性值。

是的,我确实看到了:

我不想围绕这个属性创建一个 bean,因为这只是一个 boolean 标志。

注意:如果我在 @Value 中添加 :default ,则构建会成功 - 但我相信这只是因为从 yaml 读取失败,并且默认使用我给出的值。

@Value("${kinesis.streaming.client.featuretoggle.kinesisSenderFeature:false}")
private boolean featureToggle;

注意:正如 @Andreas 在评论中指出的,我尝试给出

//In application.yml
kinesisSenderFeature:false

//In code
@Value("${kinesisSenderFeature}")
private boolean featureToggle;

即使这样也行不通。但是从 yaml 读取其他属性没有任何问题。我认为默认情况下应该读取 src/main/resources 中的标准 application.yml 吗?

任何帮助将不胜感激。谢谢!

最佳答案

正如 @pvpkiran 指出的,您不需要 PropertySourcesPlaceholderConfigurer。只需将 application.yml 放在类路径中,Spring Boot 就会拾取它并分配 Boolean 值。效果非常好,刚刚使用 Spring Boot 1.5.2 进行了测试。

关于java - Springboot yaml配置不读取 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43919706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com