Yaml基本语法
大小写敏感
使用缩进表示层级关系
缩进时不允许使用Tab键,只允许使用空格。
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
#
表示注释,从这个字符一直到行尾,都会被解析器忽略。
YAML 支持的数据结构有三种。
对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
纯量(scalars):单个的、不可再分的值
spring boot配置
Spring Boot
最大的特色是约定优先配置
,大量的默认配置对开发者十分的友好。但是在实际的应用开发中,默认配置不可能满足所有场景,同时用户也需要一些必须的配置项,比如数据库连接信息。Spring Boot
同时支持application.properties
或者application.yaml
文件
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=db_user
spring.datasource.password=db_password
YAML
格式更加简洁:
spring:
jpa:
hibernate:
ddl-auto: create
datasource:
url: jdbc:mysql://localhost:3306/db_example
username: db_user
password: db_password
一旦发现这些信息,Spring Boot
就会根据它们创建DataSource
对象
多环境YAML文件
可以使用spring.profiles
来指定配置内容属于哪一种环境,也可以把配置内容写到application_prod.yml
和application_dev.yml
.
spring.profile.active
环境属性来指定哪些配置文件处于活动状态
spring:
profiles:
active: dev
spring:
profiles: dev
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_dev
username: dev_user
password: dev_password
spring:
profiles: prod
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_prod
username: prod_user
password: prod_password
配置文件数据的读取
在application.yml
文件中加上:
yaml-info:
simpleProp: simplePropValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Vavlue2
mapProps:
key1: value1
key2: value2
java类获取yml文件的内容
package hello;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "yaml-info")
public class YmlConfig {
String simpleProp;
private String[] arrayProps;
private List<Map<String, String>> listProp1 = new ArrayList<>();
private List<String> listProp2 = new ArrayList<>();
private Map<String, String> mapProps = new HashMap<>();
public String getSimpleProp() {
return simpleProp;
}
public void setSimpleProp(String simpleProp) {
this.simpleProp = simpleProp;
}
public String[] getArrayProps() {
return arrayProps;
}
public void setArrayProps(String[] arrayProps) {
this.arrayProps = arrayProps;
}
public List<Map<String, String>> getListProp1() {
return listProp1;
}
public void setListProp1(List<Map<String, String>> listProp1) {
this.listProp1 = listProp1;
}
public List<String> getListProp2() {
return listProp2;
}
public void setListProp2(List<String> listProp2) {
this.listProp2 = listProp2;
}
public Map<String, String> getMapProps() {
return mapProps;
}
public void setMapProps(Map<String, String> mapProps) {
this.mapProps = mapProps;
}
}
通过依赖注入就可以获取该对象
@Autowired
private YmlConfig config;
@GetMapping(path = "/yamlinfo")
public @ResponseBody YmlConfig getYmlConfig() {
return config;
}