Springboot使用一个全局的配置文件,配置文件名称是固定的。
- application.properties: 语法结构:Key=value
- application.yaml: key: 空格 value
配置文件的作用:修改SpringBoot自动配置的默认,因为Springboot在底层都给我们自动配置好了。
# k=v
#对空格的要求极为严格
# 普通的key-value
name: li
# 对象
student1:
name: li
age: 3
#行内写法
student: {name:li,age: 3}
pets:
- cat
- dog
- pig
pets1: [cat,dog,pig]
yaml可以给实体类赋值,
person:
name: yy
age: 3
happy: false
birth: 2019/11/02
maps: {k1: v1,k2: v2}
lists:
- code
- music
- gril
dog:
name: ww
age: 3
要与person中的内容一一对应;person类
package com.li.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
public Person() {
}
public Person(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
this.name = name;
this.age = age;
this.happy = happy;
this.birth = birth;
this.maps = maps;
this.lists = lists;
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getHappy() {
return happy;
}
public void setHappy(Boolean happy) {
this.happy = happy;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", happy=" + happy +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
}
【注】对于@ConfigurationProperties(prefix = “person”)报红问题,要在pom.xml中添加依赖
<!-- 解决@ConfigurationProperties(prefix = "person")报红-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
@ConfigurationProperties作用:将配置文件中配置的每一个属性的值,映射到组件中;告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定,参数prefix = “person”:将配置文件中的person下面的属性一一与应。只有这个组件是容器的组件,才能使用容器提供的@ConfigurationProperties功能。