YAML基本语法
k:(空格)v:表示一对键值,其中,空格必须有,因为是以空格缩进来控制层级,左对齐表示同阶级。
例如:
server
port:8081
path:/hello
port,path表示同一阶级
值的写法
①字面量:普通值(数字,字符串,布尔值)
“”:双引号,不会转义字符串里的特殊字符,特殊字符作为本身的意思。
‘’:单引号,会转义特殊字符,例如/n转移后直接输出/n。
②对象、Map(属性和值)也就是键值对
例:
friend:
name:xl
age:21
行内写法:
friend:{name:xl,age:21}
③数组(List,Set)
写法:
pest:
-cat
-dog
-pig
行内写法
pets:[cat,dog,pig]
实战演练,获取配置文件值
一、创建bean文件夹,文件夹中创建person文件,书写其相关属性
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastname;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object>maps;
private List<Object> lists;
private Dog dog;
}
注解作用:
①@ConfigurationProperties告诉springboot将本类中所有属性和配置文件中相关配置进行绑定
prefix = “person”:配置文件中为"person"的下面的属性进行一一映射
② @Component是只有这个组件是容器中组件,才能使用容器提供的@ConfigurationProperties功能
注:使用Alt+Ins快速创建Setter and Getter方法,toString
二、创建tml文件并在yml中书写配置
server:
port: 8081
person:
lastname: 海峰
age: 21
boss: false
birth: 2000/05/03
maps: {k1:v1,k2:12}
lists:
- 佟丽娅
- 张学友
dog:
name: 小狗
age: 2
三、在test中进行单元测试
/*
* @SpringBootTest表明这是个SpringBoot单元测试
*
* @RunWith(SpringRunner.class)测试期间方便类似编码进行自动注入功能
* */
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.printf(String.valueOf(person));
}
}
四、测试结果
测试成功
五、总结
此次测试并不太完美,有警告提出:
对此,推测应为Junit的问题,最后警告未能解决。