spring|spring boot 读取 application.yml 中 List 类型数据

开发环境

  • spring boot 1.5.9
  • jdk 8
先说背景 使用 spring boot 开发应用, 有一个读取 application.yml 配置的需求,配置项的类型为列表,需要将配置项内容读取到 Java 类中, 开发过程中遇到无法正确读取配置内容的问题,遂记录.
再说干货 1. application.yml 中配置
spring boot 中默认的 yaml 类库为 snakeyaml, 目前支持 yaml 1.1 规范, 规范参考地址 YAML 1.1 (2nd Edition)
配置内容如下:
my: config: referers: - id: aaa referer: http://www.baidu.com - id: bbb referer: http://wwww.163.com

2. 相关 Java 类
配置读取类, 重点如下:
  • 多层级配置名称, 可以使用 @ConfigurationProperties(prefix = "my.config")
  • 需要 new 一个空的配置项列表 ArrayList (referers)
  • 需要生成该 List 对象的 Getter Setter 方法 (不配置无法读取数据)
@Service @ConfigurationProperties(prefix = "my.config") public class ConfigServiceImpl implements ConfigService {private static Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class); /** * 配置项列表 */ private List referers = new ArrayList<>(); public List getReferers() { return referers; }public void setReferers(List referers) { this.referers = referers; }// ... 其它业务方法 }

列表中单个元素对象:
public class Referer { private String id; private String referer; // ... 此处省去getter setter }

结束语 【spring|spring boot 读取 application.yml 中 List 类型数据】以上为实际开发中相关内容, 遇到点小坑, 解决后随手记录

    推荐阅读