读取yml文件内容变成java实体类

1.application.yml文件如下

id: 19
name: 你好
type:
  relId: 37

2.maven依赖

        <dependency>
            <groupId>com.fasterxml.jackson.dataformatgroupId>
            <artifactId>jackson-dataformat-yamlartifactId>
            <version>2.11.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.11.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.11.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.11.1version>
        dependency>

3.实体类:

public class Student {
    private Long id;
    private String name;
    private Relation type;
}
public class Relation {
    private Integer relId;
}

4.主程序:

public class ConfigBean {
    public static void main(String[] args) {
       ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            Student student = mapper.readValue(new File("D:\\tests\\src\\main\\resources\\conf\\application.yml"), Student.class);
            System.out.println(student);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java篇)