Jee*_*evs 5 java yaml spring-boot
我是Springboot的新手。这是我要解决的问题。我有一个具有以下属性的application.yml文件:
kinesis:
streaming:
client:
featuretoggle:
kinesisSenderFeature: true
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下代码访问KinesisSenderFeature的值:
@Value("${kinesis.streaming.client.featuretoggle.kinesisSenderFeature}")
private boolean featureToggle;
Run Code Online (Sandbox Code Playgroud)
以及
@Value("${kinesis.streaming.client.featuretoggle.kinesisSenderFeature}")
private Boolean featureToggle;
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试构建时,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}]
Run Code Online (Sandbox Code Playgroud)
我觉得很奇怪,它正在尝试将字符串[[$ {kinesis.streaming.client.featuretoggle.kinesisSenderFeature}]转换为布尔值,而且我相信-不会从yaml文件读取属性的值。
是的,我确实看到了:
我不想围绕此属性创建一个bean,因为这只是一个布尔标志。
注意:如果我在@Value中放置:default,则构建成功-但我相信这仅是因为从yaml读取失败,并且默认使用我提供的值。
@Value("${kinesis.streaming.client.featuretoggle.kinesisSenderFeature:false}")
private boolean featureToggle;
Run Code Online (Sandbox Code Playgroud)
注意:正如@Andreas在评论中指出的那样,我尝试给
//In application.yml
kinesisSenderFeature:false
//In code
@Value("${kinesisSenderFeature}")
private boolean featureToggle;
Run Code Online (Sandbox Code Playgroud)
即使那也不起作用。但是从yaml读取的其他属性也没有任何问题。我认为应该默认读取src / main / resources中的标准application.yml吗?
任何帮助将不胜感激。谢谢!
正如@pvpkiran 指出的,您不需要PropertySourcesPlaceholderConfigurer. 只需将其放在application.yml类路径上,Spring Boot 就会拾取它并分配Boolean值。效果非常好,刚刚使用 Spring Boot 1.5.2 进行了测试。
| 归档时间: |
|
| 查看次数: |
5839 次 |
| 最近记录: |