[英]How can I write and read to and from a application.yaml at runtime using java code in a spring boot application?
[英]How can I read in a list of objects from yaml using Spring's PropertiesConfigurationFactory?
如果我有一組屬性,我知道Springboot的寬松數據綁定器將讀取屬性列表(或yaml)並填充匹配的對象。 像這樣:
Properties props = new Properties();
props.put("devices.imports[0]","imp1");
props.put("devices.imports[1]","imp2");
props.put("devices.definitions[0].id","first");
props.put("devices.definitions[1].id", "second");
DeviceConfig conf = new DeviceConfig();
PropertiesConfigurationFactory<DeviceConfig> pcf = new PropertiesConfigurationFactory<>(conf);
pcf.setProperties(props);
conf = pcf.getObject();
assertThat(conf.getDefinitions()).hasSize(2); //Definitions is coming in as 0 instead of the expected 2
DeviceConfig看起來像這樣:
@ConfigurationProperties(prefix="devices")
public class DeviceConfig {
private List<String> imports = new ArrayList<>();
private List<DeviceDetailsProperties> definitions = new ArrayList<>();
public List<String> getImports() {
return this.imports;
}
public List<DeviceDetailsProperties> getDefinitions() {
return definitions;
}
public void setImports(List<String> imports) {
this.imports = imports;
}
public void setDefinitions(List<DeviceDetailsProperties> definitions) {
this.definitions = definitions;
}
}
DeviceDetailsProperties
僅有一個帶有getters / setter的id
字段。
奇怪的是,定義(對象)或導入(字符串)都沒有被填充。
使用SpringBoot 1.2.0.RELEASE
當以這種手動方式使用PropertiesConfigurationFactory
時,它不會自動在注釋中使用prefix
值。
添加目標targetName
如下所示:
pcf.setTargetName("devices");
更正后的代碼將是:
Properties props = new Properties();
props.put("devices.imports[0]","imp1");
props.put("devices.imports[1]","imp2");
props.put("devices.definitions[0].id","first");
props.put("devices.definitions[1].id", "second");
DeviceConfig conf = new DeviceConfig();
PropertiesConfigurationFactory<DeviceConfig> pcf = new PropertiesConfigurationFactory<>(conf);
pcf.setProperties(props);
pcf.setTargetName("devices"); // <--- Add this line
conf = pcf.getObject();
assertThat(conf.getDefinitions()).hasSize(2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.