yaml中的数组类型取值
yaml中简单的风格,十分受大家的欢迎
先说下简单的配置如何取值
1 2 3 4 5 6 7 8 9 10 11 12 |
# application-dev.yml testValue: testValueChild: testValueChildValue ... // SomeServiceImpl.java @Service public class SomeServiceImpl { // 这样就可以直接拿到配置信息啦 @Value ( "${testValue.TestValueChild}" ) private String testValueChild; ... } |
有些时候我们会需要一些数组类型,下面简单介绍一种配置信息为数组的写法,比如我们有以下格式的配置,数据同步是否开启,以及数据同步需要同步的数据类型,
1 2 3 4 5 6 |
dataSync: enable: true type: - "1" - "2" - "3" |
此时无法使用@Value取值,可通过如下方式取值,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
... // 单独注册一个bean,用于存储这类配置信息 @Component @Data @ConfigurationProperties (prefix = "data-sync" ) public class DataSyncConfig { private Boolean enable; private List<String> types; } ... public class SomeServiceImpl{ @AutoWired private DataSyncConfig dataSyncConfig;
public void youerMethod() { List<String> types = dataSyncConfig.getTypes(); } } |
springboot配置文件yml的数组形式
配置文件
1 2 3 4 |
proxy: url: - "http://www.baidu.com" - "http://www.jd.com" |
实体类
1 2 3 4 5 6 7 8 |
@Data @NoArgsConstructor @AllArgsConstructor @Configuration @ConfigurationProperties (prefix = "proxy" ) public class ProxyConfig { private String[] url; } |
对象里面的引用名字(‘url'),必须和yml文件中的(‘url')一致,不然就会取不到数据。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。原文链接:https://www.jianshu.com/p/20a11d185493
查看更多关于SpringBoot yaml中的数组类型取值方式的详细内容...