0
点赞
收藏
分享

微信扫一扫

springboot-Environment获取单独的值,ConfigurableEnvironment获取整个配置文件

小月亮06 2022-03-18 阅读 61

1、起因

今天使用Environment去拿nacos的配置文件的值,需求是把 所有的值都拿到,跟踪了半天源码,看了看关系,发现这个Environment 貌似只能去getProperty("key"),这样出来的就是单独的一个value,之后发现一个Environment的子接口,代码如下

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.core.env;

import java.util.Map;

public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
    void setActiveProfiles(String... var1);

    void addActiveProfile(String var1);

    void setDefaultProfiles(String... var1);

    MutablePropertySources getPropertySources();

    Map<String, Object> getSystemProperties();

    Map<String, Object> getSystemEnvironment();

    void merge(ConfigurableEnvironment var1);
}

如果你也debug了你会发现,有propertysources 还有propertyList类似这些,研究了会代码,根据

getProperty源码,实现获取整个配置文件,存放map返回,代码如下
controller使用层需要注入
import org.springframework.core.env.ConfigurableEnvironment;
@Autowired
private ConfigurableEnvironment configurableEnvironment;

==================================分隔符=================================================
 
public static Map<String, String> assembleList(ConfigurableEnvironment configurableEnvironment) {
        //感兴趣的可以去看getProperty的源码,跟着看看就行
        MutablePropertySources o = configurableEnvironment.getPropertySources();
        Iterator var4 = o.iterator();
        Map map = new HashMap();
        while (var4.hasNext()) {
            PropertySource<?> propertySource = (PropertySource) var4.next();
            String name = propertySource.getSource().toString();
            map.putAll(convertMap(name));
            //业务代码忽略
            if (map.containsKey("chinaImage_server")) {
                break;
            }
        }
        return map;
    }


  public static Map convertMap(String name) {
        if (!name.equals("{}") && name.startsWith("{")) {
            List<String> list = Arrays.asList(name.split(","));
            Map resMap = new HashMap();
            for (String item : list) {
                //这块处理的不好,因为有的串有可能两个==的情况,不做过多处理,只提供思路
                String key = item.substring(1, item.indexOf("="));
                String value = item.substring(item.indexOf("=") + 1);
                if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)) {
                    resMap.put(key, value);
                } else {
                    continue;
                }
            }
            return resMap;
        }
        return new HashMap();
    }

如果有官方或者更简洁的办法,请一定留言,鼓捣一个多小时,记录下

举报

相关推荐

0 条评论