是否可以使用 Spring 和 @Value 注释将 YAML 属性读入 Map [英] Is it possible to read YAML property into Map using Spring and @Value annotation
本文介绍了是否可以使用 Spring 和 @Value 注释将 YAML 属性读入 Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做的是:
YAML:
features:
feature1: true
feature2: false
feature3: true
代码:
@Value("${features}")
private Map<String,Boolean> features;
我不知道要使用什么 Spring 脚本语法来执行此操作(如果可能的话)
I can't figure out what Spring scripting syntax to use to do this (if it's possible at all)
推荐答案
我正在使用 Spring Boot 并像这样访问自定义变量:
I'm using Spring Boot and access custom variables like this:
创建一个映射到您的自定义属性的自定义类:
Create a custom class that maps to your custom properties:
@Component
@ConfigurationProperties(prefix="features")
public class ConstantProperties {
private String feature1;
public String getFeature1(){
return feature1;
}
public void setFeature1(String feature1) {
this.feature1 = feature1;
}
}
YAML 文件将如下所示:
YAML file will look like this:
features:
feature1: true
feature2: false
feature3: true
在您要访问这些属性的类中,您可以使用以下内容:
in your class that you want to access these properties, you can use the following:
@Autowire
private ConfigurationProperties configurationProperties;
然后要在该类中访问,请使用以下语法:
Then to access in that class, use the following syntax:
configurationProperties.getFeature1();
或者您可以引用自定义属性,例如:
Or you can reference the custom property like:
"{{features.feature1}}"
这篇关于是否可以使用 Spring 和 @Value 注释将 YAML 属性读入 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文