application.yml
是springboot
的配置文件yaml
基本语法
# yaml文件对空格的要求特别严格
# 普通的key-value
name: xkui
# 对象
student:
name: xkui
age: 21
# 对象的行内写法
teacher: {name: ljji,age: 34}
# 数组
pet: [cat,panda,dog]
animal:
- cat
- dog
- tiger
-
yaml可以直接给实体类赋值
-
Dog类
@Data @Component public class Dog { @Value("旺财") String name; @Value("3") Integer age; }
-
Person类
@Data @Component @ConfigurationProperties(prefix = "person") //@ConfigurationProperties(prefix = "person") 将该实体类匹配配置文件里person类对应的内容 public class Person { String name; Integer age; Boolean happy; Date birthday; Map<String,Object> maps; List<Object> list; Dog dog; }
-
yaml配置文件
person: name: 星时 age: 3 happy: false birthday: 2021/04/07 maps: {k1: v1,k2: v2} list: - code - music - cat dog: name: 旺财 age: 1
-
测试类及其运行结果
@SpringBootTest @RunWith(SpringRunner.class) public class SpringbootDemo01ApplicationTests { @Autowired private Person person; @Test public void contextLoads() { System.out.println("person = " + person); } }
运行结果: person = Person(name=星时, age=3, happy=false, birthday=Wed Apr 07 00:00:00 CST 2021, maps= {k1=v1, k2=v2}, list=[code, music, cat], dog=Dog(name=旺财, age=1))
-