引入问题:application.properties中如何配置多个学生(姓名,年龄),然后如何在springboot中绑定呢
配置文件
配置文件中定义三个学生,包含name和age
properties:
properties
school.students[0].name=John
school.students[0].age=20
school.students[1].name=Jane
school.students[1].age=22
school.students[2].name=Bob
school.students[2].age=21
或者yml:
yaml
school:
students:
- name: John
age: 20
- name: Jane
age: 22
- name: Bob
age: 21
配置类
定义一个Java类来保存学生的信息。使用@ConfigurationProperties注解指定属性前缀,并使用@Component或@Configuration注解将其注册为Spring Bean。
clike
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "school")
public class SchoolProperties {
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public static class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
在服务类中使用
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class SchoolService {
private final SchoolProperties schoolProperties;
@Autowired
public SchoolService(SchoolProperties schoolProperties) {
this.schoolProperties = schoolProperties;
}
public List<SchoolProperties.Student> getAllStudents() {
return schoolProperties.getStudents();
}
public Optional<SchoolProperties.Student> getStudentByName(String name) {
return schoolProperties.getStudents().stream()
.filter(student -> student.getName().equalsIgnoreCase(name))
.findFirst();
}
public void printAllStudents() {
schoolProperties.getStudents().forEach(student ->
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge())
);
}
public void printStudentByName(String name) {
Optional<SchoolProperties.Student> studentOpt = getStudentByName(name);
studentOpt.ifPresent(student ->
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge())
);
}
}