• Spring手动绑定ConfigurationProperties


    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());
        }
    
    }

    运行结果:

    image

  • 相关阅读:
    Flink 架构和拓扑概览
    Flink 如何背压
    流式计算的时间模型
    流式计算的背压问题
    大数据流式计算容错方案演进之路
    Flink 任务提交
    Flink wordCount
    线性回归和逻辑回归的区别
    Nginx反向代理后配置404页面
    Httpclient 实现带参文件上传
  • 原文地址:https://www.cnblogs.com/xiongmaotailang/p/5413617.html
Copyright © 2020-2023  润新知