前言
Springboot中自定义配置文件比较简单,主要是介绍Bean中类型为 List、Map、map<String, Bean>时候读取的方式,示例如下:
JAVA Properties
@Data
@Component
@ConfigurationProperties(prefix = "msg.sms")
public class SmsProperties {
private String key;
private Info info;
private Map<String, Template> templateMap;
private List<Template> templateList;
@Data
public static class Template{
private String code;
private String params;
private String desc;
}
@Data
public static class Info{
private String username;
private String name;
}
配置方式 之 application-*.yml
msg:
sms:
# 配置 普通
key: 1231255
# 配置 Bean
info:
name: test
username: test
# 配置 Map
template-map:
key1:
code: 1
params: 1
desc: 1
key2:
code: 2
params: 2
desc: 2
# 配置 list
template-list:
- code: code1
params: params1
desc: desc1
- code: code2
params: params2
desc: desc2
配置方式 之 application-*.properties
# 普通配置
msg.sms.key=1231255
# bean 配置
msg.sms.info.name: test
msg.sms.info.username: test
# Map<String, bean> 配置
msg.sms.template-list[0].code= 1
msg.sms.template-list[0].params= 1
msg.sms.template-list[0].desc= 1
msg.sms.template-list[1].code= 1
msg.sms.template-list[1].params= 1
msg.sms.template-list[1].desc= 1
# Map<String, bean> 配置
msg.sms.template-map.key1.code= code1
msg.sms.template-map.key1.params= params1
msg.sms.template-map.key1.desc= desc1
msg.sms.template-map.key2.code= code1
msg.sms.template-map.key2.params= params1
msg.sms.template-map.key2.desc= desc1
效果
debug中,已经可以看到配置项已经加载进来了。
