SpringBoot yaml数组取值 SpringBoot yaml中的数组类型取值方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot yaml数组取值 SpringBoot yaml中的数组类型取值方式

五洋捉鳖zz   2021-09-09 我要评论
想了解SpringBoot yaml中的数组类型取值方式的相关内容吗,五洋捉鳖zz在本文为您仔细讲解SpringBoot yaml数组取值的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot,yaml,数组类型取值,数组取值,下面大家一起来学习吧。

yaml中的数组类型取值

yaml中简单的风格,十分受大家的欢迎

先说下简单的配置如何取值

# application-dev.yml
 testValue:
  testValueChild: testValueChildValue
...
// SomeServiceImpl.java
@Service
public class SomeServiceImpl {
 // 这样就可以直接拿到配置信息啦
  @Value("${testValue.TestValueChild}")
  private String testValueChild;
 ...
}

有些时候我们会需要一些数组类型,下面简单介绍一种配置信息为数组的写法,比如我们有以下格式的配置,数据同步是否开启,以及数据同步需要同步的数据类型,

dataSync:
  enable: true
  type: 
    - "1"
    - "2"
    - "3"

此时无法使用@Value取值,可通过如下方式取值,

...
// 单独注册一个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的数组形式

配置文件

proxy:
    url:
    - "http://www.baidu.com"
    - "http://www.jd.com"   

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Configuration
@ConfigurationProperties(prefix = "proxy")
public class ProxyConfig {
    private String[] url;
}

对象里面的引用名字(‘url'),必须和yml文件中的(‘url')一致,不然就会取不到数据。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们