import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class PropertiesLoadUtil {
private final static Logger logger = Logger.getLogger(PropertiesLoadUtil.class);
//缓存不同properties文件内容
private static Map<String,Properties> cacheProperties = new HashMap<String,Properties>();
//配置文件缓存时效控制
private static Map<String,Long> preLoadTime = new HashMap<String,Long>();
//动态加载间隔时长 5分钟
private static final int DYNAMIC_LOAD_TIME = 300000;
/**
* 获取指定propertis 文件的Properties对象
* @param fileName
* @return
*/
public static Properties getProperties(String resourceName){
return loadProperties(resourceName);
}
/**
* 获取指定文件 的指定属性值
* @param key
* @param fileName
* @return
*/
public static String getPropertiesValue(String key,String resourceName){
return StringUtils.trim(getDynamicProperty(key,resourceName));
}
//动态获取配置文件,当缓存配置信息超过5分钟后重新缓存
private static String getDynamicProperty(String key,String resourceName){
long currentTime = System.currentTimeMillis();
if(null==preLoadTime.get(StringUtils.upperCase(resourceName)) ||
DYNAMIC_LOAD_TIME <= (currentTime-preLoadTime.get(StringUtils.upperCase(resourceName)).longValue()) ){
logger.debug("PropertyLoadUtils reload pss.properties begin");
loadPropertiesCache(resourceName);
logger.debug("PropertyLoadUtils reload pss.properties end");
}
return StringUtils.trim(cacheProperties.get(StringUtils.upperCase(resourceName)).getProperty(key));
}
//加载配置文件,并缓存
private static void loadPropertiesCache(String resourceName){
Properties prop = loadProperties(resourceName);
cacheProperties.put(StringUtils.upperCase(resourceName), prop);
preLoadTime.put(StringUtils.upperCase(resourceName), Long.valueOf(System.currentTimeMillis()));
}
//加载配置文件
private static Properties loadProperties(String resourceName){
try {
//获取当前ClassPath的绝对URI路径
ClassLoader classLoaderToUse = Thread.currentThread().getContextClassLoader();;
if (classLoaderToUse == null) {
classLoaderToUse =PropertiesLoadUtil.class.getClassLoader();
}
Enumeration<URL> urls = classLoaderToUse != null ? classLoaderToUse.getResources(resourceName) :
ClassLoader.getSystemResources(resourceName);
//读取配置文件内容
Properties props = new Properties();
while (urls.hasMoreElements()) {
URL url = (URL)urls.nextElement();
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
try{
props.load(is);
}finally{
is.close();
}
}
return props;
} catch (IOException e) {
logger.debug("load propertis "+resourceName+" is error",e);
return new Properties();
}
}
}