创建一个SpringBoot项目
用上一篇文章的方法创建一个名为springboot-2-config的项目,并删除多余文件,保留.idea,src,resources,test
在resources目录下创建一个yaml文件
说明一下yaml的语法:以冒号表示键值对
因此yaml可以给属性赋值 ,那么如何实现呢
在Application类的同级文件夹下写Dog,Person
Dog类
public class Dog {
private String name;
private Integer age;
public Dog() {
}
public Dog(String name, Integer age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Person类(成员包含Dog类对象)
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 +
'}';
}
}
先说下,如果不用yaml,用Spring的属性注入也可
以给Dog属性赋值为例:
加上@Value注解,给普通属性赋值:
类上要加上@Component!!!
然后找到test包下的自动生成的测试类:
测试结果如下:
回到用yaml文件对属性赋值
以对Person类的属性的赋值为例(属性类型比较全):
在yaml文件里写出:
在Person上加上两个注解,第一个注解不用说,创建bean实例
测试类:
测试结果:
Person{name='zhanglei', age=23, happy=false, birth=Tue Feb 17 00:00:00 CST 1998, maps={k1=v1, k2=v2}, lists=[magic, music, girl], dog=Dog{name='旺财', age=3}}