目录
一 yaml数据格式
容易阅读
重数据,轻格式
文件扩展名:yml、 yaml
yaml语法规则:
1 大小写敏感
2 属性层级关系用多行描述,每行结尾用:结束
3 用空格表示缩进层级关系(不用tab)
4 属性值前面添加空格 → 属性名:(空格)属性值
5 #注释
核心规则:属性名冒号后面与数据之间有一个空格
备注:
写字符串和写数字一样,没有引号
可以用""包裹特殊字符串(比如字符串中间有空格)
空用~表示
二 读取yaml数据
yaml:
country: China
city: shanghai
#数组
likes:
- game
- football
- food
#数组写法2
likes2: [game,music,sleep]
#表示多个user
user:
- name: user
age: 12
- name: hong
age: 8
- name: lisi
age: 9
#表示多个user第2种写法
user2:
-
name: user
age: 12
-
name: hong
age: 8
-
name: lisi
age: 9
#表示多个user第3种写法
user3: [{name: 张三,age: 18},{name: lisi,age: 12}]
controller:
package com.qing.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${country}")
private String country1;
//数组
@Value("${likes[1]}")
private String likes1;
//数组对象的值
@Value("${user3[1].age}")
private String age1;
@GetMapping
public String getById() {
System.out.println("console:SpringBoot is running:config");
System.out.println("country1:" + country1);
System.out.println("likes:" + likes1);
System.out.println("age:" + age1);
return "rest:SpringBoot is running:config";
}
}
结果
三 yaml数据引用、转义字符
yaml
baseDir: c:\windows
tempDir: ${baseDir}\temp
#加引号解析转义字符
tempDirSpecial: "${baseDir}\temp"
@Value("${tempDir}")
private String tempDir1;
@Value("${tempDirSpecial}")
private String tempDirSpecial;
四 使用自动装配读取yaml数据
import org.springframework.core.env.Environment;
//使用自动转配将所有的数据封装在对象Environment中
@Autowired
//注意导包是springframework下的
private Environment env;
public String getById() {
System.out.println("----------------------");
//getProperty括号里写的和${}大括号里的数据是一样的
System.out.println(env.getProperty("user2[1].name"));
}