微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无需Spring即可读取和映射属性文件

如何解决无需Spring即可读取和映射属性文件

我有一个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的情况下进行操作。有想法吗?

解决方法

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

根据您的情况,您可以执行以下操作:

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

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

FileProperties.class

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

MyClass

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包含有关在加载类时要使用的类的信息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。