簡體   English   中英

如何使用Spring的PropertiesConfigurationFactory從yaml中讀取對象列表?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM