读取yml文件里的list配置
YAML 支持以下几种数据类型:
对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
纯量(scalars):单个的、不可再分的值
这里只介绍list类型的读取
yml里的list配置(以 -
开头的行表示构成一个数组:):
weixin:
configs:
- schId: 111
appId: 11111
appSecret: 11111
templateId: 111111
- schId: 2222
appId: 222222
appSecret: 2222222
templateId: 2222222
导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
写一个微信配置的实体类,将配置文件中配置的每一个属性的值,映射到这个实体类中
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Data
@ConfigurationProperties(prefix = "weixin")
public class WxConfig {
private List<Config> configs;
@Data
public static class Config {
private Integer schId;
private String appId;
private String appSecret;
private String templateId;
}
}
拿到配置文件里的内容
1.注入该实体类
@Autowired
private WxConfig wxConfig;
2.解析,我这里是将其转为学校id为key的map,方便我后面使用,按照自己想要的读取就好了JSON.toJSONString(wxConfig)
public Map<Integer,Map> getWeiXinConfig(){
JSONObject o = JSON.parseObject(JSON.toJSONString(wxConfig));
JSONArray jsonArray = o.getJSONArray("configs");
Map<Integer,Map> map = new HashMap<>();
if (jsonArray.size() != 0) {
for (int j = 0; j < jsonArray.size(); j++) {
Map map2 = new HashMap();
JSONObject o1 = jsonArray.getJSONObject(j);
String appId = o1.getString("appId");
String appSecret = o1.getString("appSecret");
Integer schId = o1.getIntValue("schId");
String templateId = o1.getString("templateId");
map2.put("appId", appId);
map2.put("appSecret", appSecret);
map2.put("schId", schId);
map2.put("templateId", templateId);
map.put(schId,map2);
}
}
return map;
}
调用方法getWeiXinConfig()
,输出map的输出结果: