Spring加载ConfigurationProperties的典型应用是自动加载(Autowired),在一些特殊的场景需要手动修改加载的Property属性。
代码实例,config类
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,测试演示只有id
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()); } }
运行结果:
时间: 2024-10-25 17:22:24