美文网首页开源框架-SpringBoot系列
Springboot yml 注入列表(字符串、对象)

Springboot yml 注入列表(字符串、对象)

作者: 杰x6770 | 来源:发表于2019-11-01 10:35 被阅读0次

一、开发环境

  • jdk:1.8
  • springboot:1.5.11.RELEASE

二、需求

  • 通过application.yml将值动态注入到各属性中
public class Clazz {
    private String str; // 字符串
    private List<String> strings; // 字符串列表
    private List<User> users; // 对象列表,脑补User中包含name和age两个属性
}

三、步骤

  1. 编写yml文件,这里命名为cust.yml,当然可以直接用application.yml,也可以用properties,异曲同工这里不展开讨论
custom:
  str: ABCD
  strings: ABC, DEF, GHI
  users:
    - { name: zhangsan, age: 20 }
    - { name: lisi, age: 22 }
  1. 代码进行Springboot配置
@Component
@PropertySource("classpath:cust.yml") // 如果是application.yml,可以忽略
@ConfigurationProperties("custom") // 或(prefix = "custom")
public class Clazz {
    private String str; // 字符串
    private List<String> strings; // 字符串列表
    private List<User> users; // 对象列表,脑补User中包含name和age两个属性
}
  1. 引入springbootconfiguration-processor依赖
<dependency>
    <groupId> org.springframework.boot </groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
 </dependency>
  1. 以上就完成了注入的配置

四、Tips

  • 普通单元素类型,例如str,可以直接用@Value("${custom.str}")的方式注入,不用配置@ConfigurationProperties
  • 字符串列表或者基本包装类型列表,直接以英文逗号,隔开,不能写成-列表形式,至少在1.5版本是这样的

相关文章

网友评论

    本文标题:Springboot yml 注入列表(字符串、对象)

    本文链接:https://www.haomeiwen.com/subject/djcfbctx.html