之前写了关于读取自定义配置的文章 springboot~yml里的自定义配置 ,而今天主要说一下对复杂配置信息的读取方法,我们简单的配置用@Value注解就可以了,而结构复杂的一般使用@ConfigurationProperties来实现,下面说一下。
config-attributes: value: 345 #对应单个值 valueArray: 1,2,3,4,5,6,7,8,9 #对应数组 valueList: #对应list -13579 -246810 valueMap: #对应map name: lili age: 20 sex: female valueMapList: #对应list<map> - name: bob age: 21 - name: caven age: 31
@SpringBootApplication @ConfigurationProperties public class BootstrapConfig { public static void main(String[] args) { SpringApplication.run(BasicApplication.class, args); } }
@Component @Getter @Setter @ConfigurationProperties(prefix = "config-attributes") @ToString public class Config { private String value; private String[] valueArray; private List<String> valueList; private HashMap<String, String> valueMap; private List<Map<String, String>> valueMapList; }
@Autowired private Config config; @Test public void readConfigNode() { System.out.println(config.toString()); }
Config(value=345, valueArray=[1, 2, 3, 4, 5, 6, 7, 8, 9], valueList=[-13579 -246810], valueMap={name=lili, age=20, sex=female}, valueMapList=[{name=bob, age=21}, {name=caven, age=31}])
总结:简单配置用@Value,复杂配置用ConfigurationProperties。