【问题标题】:Read and map property file without Spring在没有 Spring 的情况下读取和映射属性文件
【发布时间】:2021-01-27 14:44:18
【问题描述】:

我有一个property.yaml 文件:

table:
  map:
    0:
      - 1
      - 2
      - 3
    1:
      - 1
      - 2
      - 3
      - 4
    2:
      - 1
      - 2
      - 3
    3:
      - 1
      - 2
      - 3

我想把它映射到Map<Integer, List<Integer>> map。使用@ConfigurationProperties("table") 很容易。但我必须在没有Spring 的情况下这样做。有什么想法吗?

【问题讨论】:

  • 使用 YAML 库。

标签: java spring properties jackson properties-file


【解决方案1】:

感谢@Adam Arold 的帮助。解决方案:

FileProperties.class

@Getter
@Setter
public class FileProperties {
    private Map<String, List<String>> table;
}

我的班级

public class MyClass {
    public FileProperties readYaml(String filename) {
        Yaml yaml = new Yaml();
        InputStream inputStream = this.getClass()
                .getClassLoader()
                .getResourceAsStream(filename);
        return yaml.load(inputStream);
    }

yaml

!!com.test.test.FileProperties
table:
  key1:
    - value1
    - value12
    - value13
  key2:
    - value11
    - value12
    - value15
  key3:
    - value11
    - value12
    - value15

注意!!com.test.test.FileProperties 包含有关加载类时要使用的类的信息。

【讨论】:

    【解决方案2】:

    Spring 使用 snakeyaml 所以它已经在你的类路径中,你可以直接使用它。如果您需要更多信息,项目页面是here

    在你的情况下,你可以这样做:

    Yaml yaml = new Yaml(new Constructor(Yourclass));
    Yourclass yc = (Yourclass) yaml.load(yourfile);
    Map<Integer, List<Integer>> map = yc.map;
    

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 2015-02-28
      • 1970-01-01
      • 2014-06-06
      • 2018-08-14
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      相关资源
      最近更新 更多