先来了解一下yaml
yaml与proprtties相比用的是 冒号加空格的方式 而不是等号
yaml可以用来表示对象数组等十分方便
#key-value键值对
name: 小虎
#对象
##方法一
Student:
name: 小虎
age: 18
##方法二 行内写法
Teacher: {name: Theshy,age: 20 }
#数组
pets:
- dog
- pig
- cat
- biard
mypets: [dog,pig]
yaml在SpringBoot中的应用
当yaml文件名为application是SpringBoot会自动扫描到他
在SpringBoot使用注解@ConfiguarationProperties(prefix="
")可以将yaml中的对象付给与之同名的java对象
Pot:
name: 二狗下凡
# 若Pot存在为该值 否则为小脑斧
type: ${Pot.name:小脑斧}}
age: ${random.int(20)}
@Component
//必须是特定的application.yaml下的 prefix 指定配置文件里的前缀
@ConfigurationProperties(prefix = "pot")
public class Pot {
private String name;
private String type;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Pot{" +
"name='" + name + '\'' +
t ", type='" + type + '\'' +
", age=" + age +
'}';
}
}
当使用的不是application文件时,可以使用注解@PropertiesResource(value=“classpath:xxx.properties”)来告诉容器文件所在位置