java - 是否可以使用 Spring 和 @Value 注释将 YAML 属性读入 Map

标签 java spring yaml spring-el

我希望能够做的是:

YAML:

features:
    feature1: true
    feature2: false
    feature3: true

代码:

@Value("${features}")
private Map<String,Boolean> features;

我无法弄清楚要使用什么 Spring 脚本语法来执行此操作(如果可能的话)

最佳答案

我正在使用 Spring Boot 并像这样访问自定义变量:

  1. 创建一个映射到您的自定义属性的自定义类:

    @Component
    @ConfigurationProperties(prefix="features")
    public class ConstantProperties {
        private String feature1;
    
        public String getFeature1(){
            return feature1;
        }
        public void setFeature1(String feature1) {
            this.feature1 = feature1;
        }
    }
    
  2. YAML 文件将如下所示:

    features:
      feature1: true
      feature2: false
      feature3: true
    
  3. 在您想要访问这些属性的类中,您可以使用以下方法:

    @Autowire 
    private ConfigurationProperties configurationProperties;
    
  4. 然后要访问该类,请使用以下语法:

    configurationProperties.getFeature1();
    
  5. 或者您可以像这样引用自定义属性:

    "{{features.feature1}}"
    

关于java - 是否可以使用 Spring 和 @Value 注释将 YAML 属性读入 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46574149/

相关文章:

java - 如何使用 apache poi 在同一个文件中写入多个工作表

java - 将样式文本写入 .docx 文件

java - 为什么我的 ApplicationContext 在我启用网络安全时无法加载?

Python 3 - 将变量导入字典

python-3.x - python yaml更新保留顺序和注释

java - Android - 可绘制路径

java - Java 中的变量垃圾回收

spring - 非响应式(Reactive)远程服务器的响应式(Reactive) WebClient

java - 无法在单个单元测试中使用 maven 的 spring-boot-starter-test 方法 - Spring Boot

ubuntu - 须藤 : no tty present and no askpass program specified in github actions