一个悲催程序猿的周六加班生活开始。。。
今天的一个需求,需要我从yml文件中获取一些配置,然后同一个配置有三个参数,差不多的意思就是需要在文件里配置一个对象数组。然后看了一下网上关于springboot获取yml配置中的数组对象的相关文章,总是有些没头没尾,就没办法让我在10分钟内搞定问题,所以在搞定之后,决定自己写一篇。。。
首先是yml数组对象的配置,网上有挺多方式的,我这里说常用的两种(注意配置的格式问题,缩进以及空格)
ant:
antaccountlist:
list:
- userId: xxxx
key: yyyyy
secret: zzzzzz
- userId: qqqq
key: wwwww
secret: eeeeee
ant:
antaccountlist:
list:
- {userId: xxxx,key: yyyy, secret: zzzz}
- {userId: qqqq,key: wwww, secret: eeeeee}
我这里使用的是第二种:注意键值对之后有一个空格
然后第二步:获取配置的数组对象,
@Configuration
@ConfigurationProperties(prefix = "ant.antaccountlist")
public class AntPoolConfigList {
private static List<AntPoolConfigs> list;//必须是static修饰,不然获取不到配置的值
public static List<AntPoolConfigs> getList() {
return list;
}
public void setList(List<AntPoolConfigs> list) {
this.list = list;
}
@Override
public String toString() {
return "AntPoolConfigList{" +
"list=" + list +
'}';
}
}
注意
1.prefix 后面的内容全部小写,不要使用驼峰,不然会报错
2.list变量一定要static修饰,不然获取不到值
附带:AntPoolConfigs 类,属性一定要包含上面yml配置的属性名
public class AntPoolConfigs {
private String userId;
private String key;
private String secret;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "AntPoolConfigs{" +
"userId='" + userId + '\'' +
", key='" + key + '\'' +
", secret='" + secret + '\'' +
'}';
}
}
这个地方,网上还有用map来封装数据,
就是在AntPoolConfigList中,变量list用Map作为数据类型
@Configuration
@ConfigurationProperties(prefix = "ant.antaccountlist")
public class AntPoolConfigList {
private static List<Map<String,String>> list;//必须是static修饰,不然获取不到配置的值
public static List<Map<String,String>> getList() {
return list;
}
public void setList(List<Map<String,String>> list) {
this.list = list;
}
}
我试过,一样可以拿到数据,但是在处理数据的时候,需要遍历map,如果需要获取特定的属性时,还需要判断参数名(这里map的k,v就会对应yml文件的键值对),就会比较麻烦;
比如我需要userId这个参数的值,还要判断entry.getKey().equals(“userId”),所以个人建议不要使用这样的方式,直接给一个对象,用get方法就能获取对应属性。
最后,调用获取数组对象的地方:
List<AntPoolConfigs> accounts = AntPoolConfigList.getList();
for(AntPoolConfigs antConfig : accounts) {
String userId = antConfig.getUserId();
System.out.println(userId)
}