User Tools

Site Tools


java-example:load-properties

一般所有的配置都是利用spring框架自动能够做到根据不同环境读取不同的配置文件。

但是有些配置是早于spring读取配置文件之前要触发的。比如加解密的密码要优先触发,拿到解密方式后,才能加载各类配置

package com.xiaosq.common;
 
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
 
/**
 * @author Morgan.L
 * @version 1.0
 * @date 2021/7/22 22:18
 */
public class PropUtil {
 
  public static final String KMS_FIRST = "kms.first";
  public static final String KMS_SECOND = "kms.second";
  public static final String KMS_THIRD = "kms.third";
 
  public static Map<String, String> props = new HashMap<>();
 
  static {
    List<String> keyList = new ArrayList<>();
    keyList.add(KMS_FIRST );
    keyList.add(KMS_SECOND );
    keyList.add(KMS_THIRD );
    fillPropertyMap(props, "application", keyList);
 
    String activeProfile = System.getProperty("spring.profiles.active");
    if (StringUtils.isNotBlank(activeProfile)) {
      fillPropertyMap(props, "application-" + activeProfile, keyList);
    }
  }
 
  private static void fillPropertyMap(Map<String, String> map, String fileName, List<String> keyList) {
    Properties prop = new Properties();
    InputStreamReader reader = null;
    InputStream inputStream = null;
    try {
      inputStream = PropUtil.class.getResourceAsStream("/" + fileName + ".properties");
      reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
      prop.load(reader);
 
      for (String key : keyList) {
        if (prop.getProperty(key) != null && StringUtils.isNotBlank((String) prop.get(key))) {
          map.put(key, (String) prop.get(key));
        }
      }
 
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(inputStream);
      IOUtils.closeQuietly(reader);
    }
  }
}
java-example/load-properties.txt · Last modified: 2021/07/29 08:47 by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki