获取配置文件的配置信息(比如数据库的配置信息,redis的配置信息) 如何让用户只能创建一个ConfigManager?单例模式:(1)把构造方法私有 (2)程序提供给别人唯一对象 单例模式的两种实现方式:饿汉方式 懒汉方式(线程不安全) 提供给别人一个唯一的ConfigManager对象,用static,使用时用 类名.方法 就行,不需要new对象,因为new的是私有化private的构造方法 懒汉方式 加一个锁synchronized,只有当第一个人用完后第二个人才能用,提高线程安全
文件名前不加“/”,则表示从当前类所在的包下查找该资源。
文件前面加“/”,则表示从当前类所在的包下查找该资源。
代码如下:
package com.ifeng.auto.api.util; import java.io.InputStream; import java.net.URL; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; public class ConfigManager { private static final Logger log = new Logger(); private static ConfigManager configManger = new ConfigManager(); private static final String defaultFileName = "auto"; private volatile static Map<String, Properties> proMap = new ConcurrentHashMap<String, Properties>(); private ConfigManager() { } public static ConfigManager instance() { return configManger; } /** * * @param profileName * 配置文件名(不包括后缀) * @param key * 属性key值 * @return */ public String getProperty(String profileName, String key) { if (key == null || profileName == null) { throw new IllegalArgumentException("key is null"); } Properties properties = proMap.get(profileName); if (properties == null) { synchronized (this) { if (properties == null) { properties = this.loadProps(profileName); if (properties != null) { proMap.put(profileName, properties); } else { return null; } } } } String value = properties.getProperty(key); return value; } public void clearProps(String proFileName) { proMap.remove(proFileName); } public String getProperty(String key) { return getProperty(defaultFileName,key); } /** * * @param profileName * 配置文件名(不包括后缀) * @param key * 属性key值 * @return */ public int getIntProperty(String profileName, String key) { if (key == null || profileName == null) { throw new IllegalArgumentException("key is null"); } String intValue = this.getProperty(profileName, key); try { return Integer.parseInt(intValue); } catch (Exception e) { //e.printStackTrace(); log.error(profileName+"."+key+"="+intValue + " has exeception:"+e.toString()); return -1; } } public int getIntProperty(String key) { return getIntProperty(defaultFileName,key); } public Properties loadProps(String proFileName) { log.debug("Getting Config"); Properties properties = null; InputStream in = null; try { properties = new Properties(); if (proFileName != null && proFileName.startsWith("http:")) { URL url = new URL(proFileName); in = url.openStream(); } else { String fileName = "/" + proFileName + ".properties"; in = getClass().getResourceAsStream(fileName); properties.load(in); } properties.load(in); log.info("Successfully proFileName=" + proFileName + " load Properties:" + properties); } catch (Exception e) { e.printStackTrace(); log.error("Error reading " + proFileName + " in loadProps() " + e.getMessage()); log.error("Ensure the " + proFileName + " file is readable and in your classpath."); } finally { try { if (in != null) in.close(); } catch (Exception e) { e.printStackTrace(); } } return properties; } }