YAML的设计者认为在配置文件中所要表达的数据内容有三种类型:标量(Scalar,如字符串和整数等)、序列(Sequence,如数组)和Mapping(类似hash的key/value pair)。
一、读取键值对
\\customer.yamlfirstName: "John"lastName: "Doe"age: 20
Yaml yaml = new Yaml();Object result= yaml.load(new FileReader("D:\\config\\customer.yaml"));
result加载为LinkedHashMap类。
二、写入键值对
Map<String,Object> object = new LinkedHashMap<>();object.put("firstName","John");object.put("lastName","Doe");object.put("age",20);Yaml yaml = new Yaml();yaml.dump(object,new FileWriter("D:\\config\\object.yaml"));return object.toString();
\\object.yaml{firstName: John, lastName: Doe, age: 20}
三、写入java对象
@Data@NoArgsConstructor@AllArgsConstructorpublic class Pojo {public int id;public String name;}
Yaml yaml = new Yaml();List<Pojo> arr = new ArrayList<>();Pojo p1 = new Pojo(1,"hello");Pojo p2 = new Pojo(2,"world");arr.add(p1);arr.add(p2);yaml.dump(arr,new FileWriter("D:\\config\\pojo.yaml"));
\\pojo.yaml- !!com.example.yamldemo.domain.Pojo {id: 1, name: hello}- !!com.example.yamldemo.domain.Pojo {id: 2, name: world}
四、读取复杂键值对
\\applicationspring:profiles:active: instance1application:name: eureka-serviceeureka:client:#由于该应用为注册中心,设置为false,表明不向注册中心注册自己register-with-eureka: falseserver:enable-self-preservation: false#是否从eureka服务器获取注册信息,这里不需要fetch-registry: falselogging:level:com:netflix:eureka: OFFdiscovery: OFFmanagement:endpoints:web:exposure:include: '*'endpoint:health:show-details: ALWAYS---spring:profiles: instance1server:port: 8761eureka:client:service-url:defaultZone: http://localhost:8762/eureka/---spring:profiles: instance2server:port: 8762eureka:client:service-url:defaultZone: http://localhost:8761/eureka/
Yaml yaml = new Yaml();Iterable<Object> result = yaml.loadAll(new FileReader("D:\\config\\application.yaml"));log.info(result.getClass());for(Object object:result){log.info(object.getClass());for(Map.Entry entry:((LinkedHashMap<Object,Object>)object).entrySet()){log.info(entry.getKey());log.info(entry.getKey().getClass());log.info(entry.getValue());log.info(entry.getValue().getClass());}}
由输出可得它们都是
五、读取java对象
\\address.yamllines: |458 Walkman Dr.Suite #292city: Royal Oakstate: MIpostal: 48046
@Data@NoArgsConstructor@AllArgsConstructorpublic class Address {private String lines;private String city;private String state;private Integer postal;}
Yaml yaml = new Yaml();Address ret = yaml.loadAs(new FileReader("D:\\config\\address.yaml"), Address.class);log.info(ret.getCity());return ret.toString();
注意
把yaml文件放入项目的时候犯了大错,文件夹定义成了config,里面又有application.yaml,所以配置文件加载错了
。
因此我去了解下yaml、properties文件加载的优先级,最高优先级是项目目录下的config文件夹里面的application,第二就是项目目录下的application,第三就是resource下的config文件夹里的application,第四就是resource的application,还有一个规则就是application.properties加载优先级比application.yaml优先级高。
