如何在Spring Boot中从属性文件读取数组表示形式

时间:2019-03-01 13:17:12

标签: spring-boot property-files

我想读取一个具有数组格式的属性文件。

我有此属性文件:

students.student[0] = ABC
students.student[0].marks[0] = 10
students.student[0].marks[1] = 20
students.student[0].marks[2] = 30
students.student[0].marks[3] = 40
students.student[0].marks[4] = 50
students.student[0].marks[5] = 60
students.student[0].marks[6] = 70

students.student[1] = XYZ
students.student[1].marks[0] = 10
students.student[1].marks[1] = 20
students.student[1].marks[2] = 30
students.student[1].marks[3] = 40
students.student[1].marks[4] = 50
students.student[1].marks[5] = 60
students.student[1].marks[6] = 70

我正尝试按以下方式读取此属性文件:

@ConfigurationProperties("students")
@PropertySource("classpath:student.properties")
public class StudentProperties{
   List<Student> students = new ArryaList<Student>();
   public static class Student
   {
      String name;
      List<Marks> marks = new ArrayList<Marks>;
      public static class Marks
      {
         int marks;
          //getters and setters
      }     
      //getters and setters
   }
   //getters and setters
 }

但这不是设置值。 该怎么做?

2 个答案:

答案 0 :(得分:1)

映射POJO的格式不正确,在Student类中只有List<Integer>

@ConfigurationProperties("students")
@PropertySource("classpath:student.properties")
public class StudentProperties{
List<Student> student = new ArryaList<Student>();
   public static class Student
      {
         String name;
         List<Integer> marks = new ArrayList<Integer>();

        //getters and setters
     }
     //getters and setters
  }

答案 1 :(得分:0)

以某种形式(Reading a List from properties file and load with spring annotation @Value)可能时,这将被视为滥用application.properties文件,该文件仅用于配置而不是用作数据存储。

我建议您将数据保存在CSV文件中,并使用许多合适的库之一(例如How to easily process CSV file to List<MyClass>

进行解析)