Spring加載ConfigurationProperties的典型應用是自動加載(Autowired),在一些特殊的場景須要手動修改加載的Property屬性。java
代碼實例,config類spring
import java.util.ArrayList; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix="devices") public class DeviceConfig { private List<String> imports = new ArrayList<String>(); private List<DeviceDetailsProperties> definitions = new ArrayList<DeviceDetailsProperties>(); 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; } }
DeviceConfig類代碼用到的DeviceDetailsProperties,測試演示只有idide
public class DeviceDetailsProperties { String id; public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return id; } }
import java.util.Properties; import org.springframework.boot.bind.PropertiesConfigurationFactory; public class Test { public static void main(String[] args) throws Exception { 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<DeviceConfig>(conf); pcf.setProperties(props); pcf.setTargetName("devices"); conf = pcf.getObject(); System.out.println(conf.getImports()); System.out.println(conf.getDefinitions()); } }
運行結果:測試