在 Spring Boot 中,application.properties
配置一会出现在项目的四个位置中,它们在项目运行时都会被读取,但具备优先级,优先级较高的将会覆盖掉其他的配置,它们优先级从高到低依次为:
- 根目录下
/config
文件夹中的 - 根目录中的
classpath
中的/config
文件夹下的classpath
根目录下的
采用 YAML 时,优先级也一样。
类型安全配置属性 (Type-safe Configuration Properties)
Spring 允许使用注解和接口,将配置文件中数据注入到 Bean 中。接下来来看一下一个简单的例子,首先在 application.properties
中添加以下内容:
student.name=Peterson Chang
student.age=21
student.id=962012
student.nationality=Singapore
而后将其注入 Bean 中:
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private int age;
private int id;
private String nationality;
// 省略 Getter 和 Setter
}
注意这里最好添加一个依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
之后用 Controller 就可以读取内容了:
@RestController
public class BookController {
private Student student;
@Autowired
public void autowiredStudent(Student _student) {
student = _student;
}
@GetMapping("/student")
public Student getStudent() {
return student;
}
}
直接对
Student student
进行 @Autowired 是可行的,但是 Intellij IDEA 不推荐这种方法,会出警告。@Autowired 一个 Setter 比较安全。
测试之后会得到相应的结果:
{"name":"Peterson Chang","age":21,"id":962012,"nationality":"Singapore"}
采用 YAML
只需要将项目中的 application.properties
文件改为 application.yml
, 并修改其中的内容就可以使用 YAML 格式作为配置文件了。YAML 的排版更为直观一点,使用方法也十分简单,这里就不再赘述。以下主要介绍 YAML 在注入对象列表 (List) 这类复杂配置的方法:
如果是项目开发到一半进行转化的话,Google 上有很多转换工具
首先,在上文的例子中,只有一位学生,这非常不合理,所以我们现在为这个学校,在 YAML 中添加更多学生的数据:
student_list:
student:
- age: 21
id: 962012
name: Peterson Chang
nationality: Singapore
hobbies:
- Reading
- Playing Guitar
- age: 22
id: 922878
name: Andy Parker
nationality: Australia
hobbies:
- Jogging
- Swimming
- Hiking
然后为它注入至 Bean 中:
@Component
@ConfigurationProperties(prefix = "student-list")
public class StudentList {
private List<Student> student;
public List<Student> getStudent() {
return student;
}
public void setStudent(List<Student> student) {
this.student = student;
}
}
Student.java
public class Student {
private String name;
private int age;
private int id;
private String nationality;
private List<String> hobbies;
//... 省略 Getter 和 Setter
}
之后添加 Controller
@RestController
public class StudentController {
private StudentList studentList;
@Autowired
public void autowiredStudentList(StudentList _studentList) {
studentList = _studentList;
}
@GetMapping("/student-list")
public StudentList getStudentList() {
return studentList;
}
}
之后测试,就可以得到相应的结果:
{"student":[{"name":"Peterson Chang","age":21,"id":962012,"nationality":"Singapore","hobbies":["Reading","Playing Guitar"]},{"name":"Andy Parker","age":22,"id":922878,"nationality":"Australia","hobbies":["Jogging","Swimming","Hiking"]}]}
这里值得注意的是:属性绑定命名规则是宽松的,如我们在 YAML 文件里面写的是
student_list
而在 Java 类中写的是StudentList
,它们是可以被匹配到的。另外如 studentList、studen-list、STUDENTLIST 等 都可以被读取到。