java 自定義讀取properties配置文件屬性
把屬性存到一個map里,并提供get方法,如果沒有獲取到值,則重新加載一遍配置文件,重新賦值,從而刷新數package com.aaa.demo.testProperties;
import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * projectName: testSpring * * @author: * time: 2023/8/1 18:11 * description: */ public class TestProPerties { private static Map propertiesMap = new HashMap();
public static void main(String[] args) throws IOException {
String name = getValue("name");
System.out.println(name);
}
/** * 獲取值,沒有值的話會重新從properties配置文件加載一遍 * @param key * @return * @throws IOException */ public static String getValue(String key) throws IOException { String value = (String) propertiesMap.get(key); if (value == null || value.length() < 1) { TestProPerties testProPerties = new TestProPerties(); testProPerties.refresh(); return (String) propertiesMap.get(key); }else { return value; } } /** * 刷新數據 * @throws IOException */ public void refresh() throws IOException { //獲取配置文件,要注意路徑問題,路徑不對會找不到文件,當前文件在SRC根目錄下 InputStream is = this.getClass().getResourceAsStream("/test11.properties"); Properties prop= new Properties(); prop.load(is); is.close(); Enumeration<?> enumeration = prop.propertyNames(); while (enumeration.hasMoreElements()) { String o = (String) enumeration.nextElement(); propertiesMap.put(o, prop.get(o)); } }
}

浙公網安備 33010602011771號