基本语法
- k:(空格)v:表示一对键值对
- v:包含上面举的数据
- k:string类型
demo
test:
name: 小李
age: 15
v:基本类型:数字,字符串,布尔
字符串默认不用加上单引号
或者双引号
;
如果字符串包含空格
或者特殊字符(例如冒号)
,需要加引号
双引号
不会对串中转义字符
进行转义
""
:双引号:不会转义字符串里面的特殊字符; 特殊字符会作为本身想表示的意思; 如 :name: "zhangsan \n lisi"
:输出;zhangsan 换行 lisi
''
:单引号:转义特殊字符 特殊字符终只是一个普通的字符串数据 , 如:name: 'zhangsan \n lisi'
:输出;zhangsan \n lisi
多行字符串可以用|
保留换行
#实际值为 line1换行line2换行line3换行
str: |
line1
line2
line3
|+
保留块尾换行
#实际值为 line1换行line2换行line3换行换行换行
str: |+
line1
line2
line3
other: ...
|-
删除串尾换行
#实际值为 line1换行line2换行line3
str: |-
line1
line2
line3
other: ...
对象、Map(属性和值)(键值对):
demo
friends:
lastName: zhangsan
age: 20
## 行内写法:friends: {lastName: zhangsan,age: 18}
数组(List、Set):
用-
值表示数组中的一个元素
pets:
‐ cat
‐ dog
‐ pig
# 行内写法 pets: [cat,dog,pig]
注入yml中的值@Value
和@ConfigurationProperties
spring:
test: 小猪
#list<map>
testList:
-
name: 小王
age: 12
-
name: 小李
age: 13
# map<String,String>
testMap:
name: 小朱
age: 14
testname: 小明
@Value
使用demo
package com.example.demo.yml;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* value 的使用
*/
@Component
public class ValueTest {
// 直接赋值
@Value("小李")
private String name;
@Value("1")
private int num;
//读取配置文件的信息
@Value("${spring.testMap.name}")
private String name2;
@Value("${spring.test}")
private String name1;
//报错
//@Value("${spring.testMap}")
private Map<String,String> map;
//使用SpEL
@Value("#{1+1}")
private int num1;
}
使用@ConfigurationProperties
注入demo
package com.example.demo;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Size;
import java.util.List;
import java.util.Map;
@Data
@Component
@ConfigurationProperties(prefix = "spring")
@Validated
public class TestConfigurationProperties {
private List<Map> testList;
private Map<String,String> testMap;
private String name;
private String test;
}