Spring Boot
yaml基本使用
#对空格的要求十分高!
#注入到我们的配置类中!
name: 小米
#对象
student:
name: 小米
age:3
#行内写法
student: {name:小埋,age: 3}
#数组
pets:
- cat
- dog
- pig
pets: [cat,dog,pig]
通过yaml给对象赋值样例
- pojo
@ConfigurationProperties(prefix = "people")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class People {
private String name;
private int age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component//声明为bean
@ConfigurationProperties(prefix = "people.dog")//扫描yaml文件中的元素
public class Dog {
private String name;
private int age;
@Bean//设置bean的id为dog01
public Dog dog01(){
return new Dog();
}
}
yaml
people:
name: 小埋
age: 8
happy: true
birth: 2020/5/8
maps: {K1: V1,K2: V2}
lists: [茶,奶,饼]
dog:
name: 终端
age: 78
- test
@SpringBootTest
class BootConfigApplicationTests {
@Resource(name = "dog01")
private Dog dog;
@Autowired
private People people;
@Test
void contextLoads() {
System.out.println(people);
System.out.println(dog);
}
}
本节注解
@ConfigurationProperties(prefix = "yaml文件中的相应前缀")
- 扫描yaml文件(application.yaml)
JSR-303
一般用来约束对象中的属性值,属性的格式,是否能为空,以及其他