我是 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}]转换为布尔值,我相信 – 不是从yaml文件中读取属性的值.
是的,我确实看到了:
> Mapping list in Yaml to list of objects in Spring Boot
> Spring boot YAML Config not reading all values
> Evaluating spring @value annotation as primitive boolean
我不想在这个属性周围创建一个bean,因为这只是一个布尔标志.
注意:如果我在@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就会选择它并指定Booleanvalue.像魅力一样工作,只是用Spring Boot 1.5.2进行测试.