Person类:
@ConfigurationProperties(prefix="person2")
实现了给person类赋值
package com.guan.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person2")
@Validated //JSR303数据格式校验
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 +
'}';
}
}
applicaton.yaml文件:
person2:
# ${random.uuid}生成随机uuid
name: xiaobai${random.uuid}
# ${random.int}生成随机int型数据
age: ${random.int}
happy: false
birth: 2019/11/02
maps: {k1: v1,k2: v2}
hello: 小白
lists:
- code
- music
- book
dog:
#注意:这里${person.hello:hello},所代表的意思是,如果person。hello有值,
# 则name的值是person。hello,如果没有值,则默认为冒号后的值
name: 主人名为:${person2.hello:无}_狗狗名为:旺财
age: 20
测试类:
@SpringBootTest
class Springboot02ConfigApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
//这里输出的person的值就是yaml里person2的各项数值
System.out.println(person);
}
}
结果:
Person{
name='xiaobai9227676-40c8-4ab6-b194-b727e4e77a31',
age=1795572801,
happy=false,
birth=Sat Nov 02 00:00:00 CST 2019,
maps={k1=v1, k2=v2},
lists=[code, music, book],
dog=Dog{name='主人名为:小白_狗狗名为:旺财', age=20}
}