每一年都奔走在自己热爱里

 
没有人是一座孤岛,总有谁爱着你

springboot 获取所有配置文件,包括外部配置

1. 使用@Value注解读取

读取properties配置文件时,默认读取的是application.properties。

    @Value("${port}")
    private String port;

2、使用Environment读取

    @Autowired
    private Environment environment;
    
    public void test(){
    String port=environment.getProperty("port")
    }

获取全局配置,加载jar包内部和外部的所有生效的配置

public void getEnvironment() {
   StandardServletEnvironment standardServletEnvironment = (StandardServletEnvironment) environment;
   Map<String, Map<String, String>> map = new HashMap<>(8);
   Iterator<PropertySource<?>> iterator = standardServletEnvironment.getPropertySources().iterator();
   while (iterator.hasNext()) {
     PropertySource<?> source = iterator.next();
     Map<String, String> m = new HashMap<>(128);
     String name = source.getName();
      //去除系统配置和系统环境配置
           if (name.equals(StandardServletEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) || name.equals(StandardServletEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) {
               continue;
           }
     Object o = source.getSource();
     if (o instanceof Map) {
       for (Map.Entry<String, Object> entry : ((Map<String, Object>) o).entrySet()) {
         String key = entry.getKey();
         m.put(key, standardServletEnvironment.getProperty(key));
       }
     }
     map.put(name, m);
   }
   return R.success(map);
 }

3.使用PropertiesLoaderUtils获取

public class PropertiesListenerConfig {
    public static Map<String, String> propertiesMap = new HashMap<>();

    private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadAllProperties(String propertyFileName) {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
            processProperties(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }

    public static Map<String, String> getAllProperty() {
        return propertiesMap;
    }
    }
posted @ 2021-12-20 21:05  与乐i  阅读(1945)  评论(0编辑  收藏  举报
Live2D
// 生成目录索引列表 //侧边栏目录索引