在项目中,习惯用YAML来写配置文件,但读取自定义配置文件时,遇到了问题:
编写两个配置文件:
1. temp.yml
prefix:
what: x
list:
- name: tech
item: 123
- name: skill
item: 987
2. temp.properties
prefix.what = x
prefix.list[0].name = a
prefix.list[0].item = 11
prefix.list[1].name = b
prefix.list[1].item = 12
编写配置类:
@PropertySource(value = "file:src/main/resources/config/temp.yml")
@ConfigurationProperties(prefix = "prefix", ignoreUnknownFields = false)
@Configuration
public class TempConfiguration {
private String what;
private List<Map<String, String>> list = new ArrayList<>();
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
public List<Map<String, String>> getList() {
return list;
}
public void setList(List<Map<String, String>> list) {
this.list = list;
}
}
这时是有问题的,what和list其实都并没有加载进去。验证:
@RequestMapping(path = "test")
@RestController
public class TempRestController {
@Autowired
TempConfiguration tempConfiguration;
@PostMapping(path = "binder")
public MyResponse binder() {
MyResponse response = new MyResponse();
System.out.println(tempConfiguration.getWhat());
for (Map<String, String> map : tempConfiguration.getList()) {
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
}
return response;
}
}
将TempConfiguration.java中的temp.yml改成temp.properties,就可以,属性都能加载进去。
参考:
YAML files cannot be loaded by using the @PropertySource
annotation. So, in the case that you need to load values that way, you need to use a properties file.
即@PropertySource不支持YAML文件。