我刚开始学春靴。这就是我想要解决的问题。我有一个具有以下属性的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文件中读取属性值。
是的,我确实看到了:
我不想在这个属性周围创建一个bean,因为这只是一个布尔标志。
注意:如果我在@Value中放置了一个:默认值,构建就会成功--但我相信这只是因为对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吗?
任何帮助都将不胜感激。谢谢!
发布于 2017-05-11 18:55:29
正如@pvpkiran所指出的,您不需要PropertySourcesPlaceholderConfigurer。只要将application.yml放在类路径上,Spring就会获取它并分配Boolean值。工作起来很有魅力,只是用SpringBoot1.5.2进行了测试。
https://stackoverflow.com/questions/43919706
复制相似问题