YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup
Language”(仍是一种标记语言)。
key: value;kv之间有空格
大小写敏感
使用缩进表示层级关系;缩进不允许使用tab,只允许空格;缩进的空格数不重要,只要相同层级的元素左对齐即可
’#'表示注释
字符串无需加引号,如果要加,’'与""表示字符串内容 会被 转义/不转义
返回顶部
k: v
# 行内写法: k: {k1:v1,k2:v2,k3:v3} # 或 k: k1: v1 k2: v2 k3: v3
# 行内写法: k: [v1,v2,v3] # 或者 k: - v1 - v2 - v3
返回顶部
package com.zyx.boot.bean; import lombok.Data; import lombok.ToString; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; @Data @ToString @Component @ConfigurationProperties(prefix = "person") // 与配置文件中前缀为person的绑定 public class Person { private String userName; private Boolean boss; private Date birth; private Integer age; private Pet pet; private String[] interests; private List<String> animal; private Map<String, Object> score; private Set<Double> salary; private Map<String, List<Pet>> allPets; }
package com.zyx.boot.bean; import lombok.Data; import lombok.ToString; @Data @ToString public class Pet { private String name; private Double weight; }
# yaml表示以上对象 person: # 字面量 userName: zhangsan boss: false birth: 2019/12/12 20:12:33 age: 18 # 对象 pet: name: tomcat weight: 23.4 # 数组 interests: [篮球,游泳] animal: - jerry - mario # Map score: # key english: # value是数组 first: 30 second: 40 third: 50 math: [131,140,148] chinese: {first: 128,second: 136} # Set salarys: [3999,4999.98,5999.99] #Map allPets: sick: - {name: tom} - {name: jerry,weight: 47} health: [{name: mario,weight: 47}]:
package com.zyx.boot.controller; import com.zyx.boot.bean.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class PersonController { @Autowired Person person; @RequestMapping("/person") @ResponseBody public Person showPerson(){ return person; } }
运行服务:可以看到在yaml配置中的属性值,都被赋到了Person对象中去了~
返回顶部
<!-- 配置自定义类提示 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- 打包时排除配置器 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </exclude> </excludes> </configuration> </plugin>
返回顶部