1 简介
为什么写关于yaml文件读取?
源于接手同事代码。
他做业务时,使用了阿里云的OSS存储服务,将配置文件以*.yml形式存储在OSS,
Java服务定时调用OSS配置文件,实现对应的业务逻辑。
配置文件存储在OSS,可以灵活变更配置,而无需重启服务或者重新部署服务。
但是,使用过程中,遇到了jar包冲突。
OSS的jar包与其他jar包中的jar包版本冲突,导致部分功能无法正常使用。
为保证所有功能正常运行,
特,将存储与OSS的yml配置文件,放在本地resources中,避免使用OSS组件。
通过yml映射实体,直接实例化实体。
2 配置
2.1 依赖
<dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.23</version>
</dependency>
2.2 yml文件
src/main/resources/test.yml
uid: 0x0001
nickname: xindaqi
sex: China
---
uid: 0x0002
nickname: xinerqi
sex: China
2.3 映射的实体
package com.monkey.java_study.common.entity;/*** User实体** @author xindaqi* @since 2021-01-23*/public class UserEntity {/*** 用户id*/private String uid;/*** 用户名称*/private String nickname;/*** 用户性别*/private String sex = "haha";public UserEntity() {}public UserEntity(String uid) {this.uid = uid;}public UserEntity(String uid, String nickname, String sex) {this.uid = uid;this.nickname = nickname;this.sex = sex;}public UserEntity copy() {return new UserEntity(uid, nickname, sex);}public String getUid() {return uid;}public void setUid(String uid) {this.uid = uid;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "UserEntity{" +"uid=" + uid +", nickname='" + nickname + '\'' +", sex='" + sex + '\'' +'}';}
}
2.4 读取yml配置
package com.monkey.java_study.functiontest;import com.monkey.java_study.common.entity.UserEntity;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;/*** 读取Yaml配置文件.** @author xindaqi* @date 2022-03-02 14:54*/
public class YamlTest {private static final Logger logger = LoggerFactory.getLogger(YamlTest.class);@Testpublic void readYamlConfiguration() {try(InputStream content = com.monkey.java_study.thirdparty.YamlTest.class.getClassLoader().getResourceAsStream("test.yml")) {Yaml yaml = new Yaml(new Constructor(UserEntity.class));Iterable<Object> its = yaml.loadAll(content);List<UserEntity> userEntityList = new ArrayList<>();for(Object it : its) {userEntityList.add((UserEntity) it);}logger.info(">>>>>>>>User:{}", userEntityList);} catch(Exception ex) {throw new RuntimeException(ex);}}
}