在spring boot web项目中将yaml文件加载到Map(而不是环境配置文件)的最佳方法是什么?

时间:2017-03-29 11:55:02

标签: spring-boot yaml

在我的数据框架图层中,我想从src/main/resources读取一个yaml。 文件名为mapconfigure.yaml。它与业务数据相关联,而不仅仅是环境配置数据。

其内容如下:

person1: 
  name: aaa
  addresses: 
    na: jiang
    sb: su
person2: 
  name: bbb
  addresses: 
    to: jiang
    bit: su

我想将此信息存储到HashMap中。

使用像@ConfigurationProperties这样的弹簧注释是否意味着什么? 如何详细实现这一目标?

此外,我无法更改文件名。这意味着我必须使用mapconfigure.yaml作为文件名,而不是application.ymlapplication.properties

我的HashMap的结构如下:

HashMap<String, Setting>

@Data
public class Setting{
  private String name;
  private HashMap<String, String> addresses
}

我的预期的HashMap &#39;如下:

{person1={name=aaa, addresses={na=jiang, sb=su}}, person2={name=bbb, addresses={to=jiang, bit=su}}}

我不确定我是否可以使用YamlMapFactoryBean类来执行此操作。

getObjectYamlMapFactoryBean方法的返回类型为Map<String, Object>,而不是通用类型,如Map<String, T>

Spring boot doc刚刚说过

  

Spring Framework提供了两个方便的类,可用于加载YAML文档。 YamlPropertiesFactoryBean将YAML作为Properties加载,YamlMapFactoryBean将YAML作为Map加载。

但是没有一个详细的例子。

更新

在github中,我创建了一个样本。 It's Here。 在此示例中,我想在myconfig.yaml类中加载theMapPropertiesSamplePropertyLoadingTest对象。 Spring启动版本为1.5.1,因此我无法使用location的{​​{1}}属性。 怎么做?

2 个答案:

答案 0 :(得分:5)

您确实可以使用@ConfigurationProperties实现此目的。

从Spring Boot 1.5.x开始(缺少@ConfigurationProperies位置attr。):

new SpringApplicationBuilder(Application.class)
    .properties("spring.config.name=application,your-filename")
    .run(args);

@Component
@ConfigurationProperties
public class TheProperties {
    private Map<String, Person> people;
    // getters and setters are omitted for brevity
}

在Spring Boot 1.3.x中:

@Component
@ConfigurationProperties(locations = "classpath:your-filename.yml")
public class TheProperties {
    private Map<String, Person> people;
    // getters and setters are omitted for brevity
}

以上示例的Person类如下所示:

public class Person {
    private String name;
    private Map<String, String> addresses;
    // getters and setters are omitted for brevity
}

我使用以下文件测试了代码:your-filename.yml 在src / main / resources中定义,内容为:

people:
  person1:
    name: "aaa"
    addresses:
      na: "jiang"
      sb: "su"
  person2:
    name: "bbb"
    addresses:
      to: "jiang"
      bit: "su"

如果您需要任何进一步的帮助,请与我们联系。

答案 1 :(得分:2)

试试这个

 YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> applicationYamlPropertySource = loader.load(
                "properties", new ClassPathResource("application.yml"), null);// null indicated common properties for all profiles.
            Map source = ((MapPropertySource) applicationYamlPropertySource).getSource();
            Properties properties = new Properties();
            properties.putAll(source);
            return properties;
        } catch (IOException e) {
            LOG.error("application.yml file cannot be found.");
        }
相关问题