通過單例模式去載入可配置的常量
阿新 • • 發佈:2019-01-27
前言:一般常量都通過public static final 寫死在程式碼裡,如果要想改常量,需要修改程式碼,很不方便。
現在將常量提出來,放到properties檔案裡,可以在程式碼外側自由修改,簡單方便。
下面,我們通過一個簡單的單例模式(由Enum實現)來優雅的load properties。
import java.io.IOException; import java.io.InputStream; import java.util.Properties; public enum ConstantConfig { CONTEXT("context.properties"); private Properties properties = new Properties(); private ConstantConfig(String path) { InputStream is = ConstantConfig.class.getClassLoader().getResourceAsStream(path); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } } public String getProperties(String key) { return properties.getProperty(key); } public String getProperties(String key, String value) { return properties.getProperty(key, value); } }