配置中心Apollo

Apollo(0) Spring Environment

2023-11-09  本文已影响0人  Oliver_Li

Environment主要用途:

Environment的使用:

Environment相关补充:

     /**
     * 替换environment里的数据,environment可以通过EnvironmentAware等等方式直接获取
     * @param propertySource 数据源的名字
     * @param key 替换的key
     * @param newValue 替换的新值
     */
    public void replaceProperties(String propertySource, String key, String newValue){
        // environment的配置源集合里有系统变量、配置文件等等
        MutablePropertySources propertySources = environment.getPropertySources();
        if(propertySources.contains(propertySource)){
            // 获取目标数据源
            PropertySource<?> bootstrapPropertySource = propertySources.get(propertySource);
            // 创建新的propertySource覆盖掉老的propertySource
            Object source = bootstrapPropertySource.getSource();
            if (source instanceof Map) {
                // 删除旧的
                propertySources.remove(propertySource);
                Map<String, Object> externalProperties = new HashMap<>((Map<String, Object>) source);
                externalProperties.put(key, newValue);
                MapPropertySource newPropertySource = new MapPropertySource(propertySource, externalProperties);
                // 添加新的数据源到优先级最高的位置
                propertySources.addFirst(newPropertySource);
            }
        }
    }


    public void print(String key) throws BeansException {
        // 使用environment获取配置
        System.out.println("Environment-----" + environment.getProperty(key));
    }
上一篇 下一篇

猜你喜欢

热点阅读