将springboot application.yml中的属性读取到Java类中

时间:2018-12-04 12:51:41

标签: spring-boot

我的application.yml文件中具有以下yaml结构

persons:
  - name: john
    age: 24
    height: 1.34
  - name: james
    age: 27
    height: 1.52

和这个Java类

@Component
@ConfigurationProperties()
public class PlayerDetails{

    private List<String> persons = new ArrayList<>();

    public String getAllPeopleDetails() {
      System.out.println("People Details: \n");

      for (String person: persons) {
        System.out.println(person);
      }
   }
 }

但是,人员列表为空。我不知道我可能做错了什么。请协助我指出正确的方法。

谢谢

1 个答案:

答案 0 :(得分:1)

像这样重新制作您的PlayerDetails:

@Component
@ConfigurationProperties()
public class PlayerDetails{

    private List<PlayerDetail> persons = new ArrayList<>();

    public static class PlayerDetail {
        private String name;
        private String age;
        private String height;


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public String getHeight() {
            return height;
        }

        public void setHeight(String height) {
            this.height = height;
        }
    }

    public String getAllPeopleDetails() {
        System.out.println("People Details: \n");

        for (PersonDetail person: persons) {
            System.out.println(person);
        }
        return "";
    }
}