PropertiesLoaderUtils是org.springframework.core.io.support包下的工具
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 读取properties文件工具类
**/
public class ReadPropertiesUtil {
private final static Logger log = LoggerFactory.getLogger(ReadPropertiesUtil.class);
//
static String PATH = new StringBuffer(Thread.currentThread().getContextClassLoader().getResource("").getPath()).append("config/properties/").toString();
static Map<String,Object> propertiesMap = new HashMap<>();
public static<T> T get(String key,String propertiesName,Class<T> t){
if (String.class.getName().equals(t.getName())) {
return (T)getString(key, propertiesName);
}else if(Integer.class.getName().equals(t.getName())){
return (T)getInteger(key, propertiesName);
}
return null;
}
public static String getString(String key,String propertiesName){
return (String)getValue(key, propertiesName);
}
public static Integer getInteger(String key,String propertiesName){
return Integer.valueOf(getString(key, propertiesName));
}
/**
* 获取值
* @param key
* @param propertiesName
* @return
*/
public static Object getValue(String key,String propertiesName){
if(propertiesName != null && !propertiesName.endsWith(".properties")){
propertiesName = new StringBuffer(propertiesName).append(".properties").toString();
}
//判断文件是否修改
isModifyFile(propertiesName);
Properties properties = (Properties) propertiesMap.get(propertiesName);
Object value = properties.get(key);
log.info("读取配置信息,key:{},value:{}",key,value);
return value;
}
/**
* 判断文件是否修改
* @param propertiesName
*/
public static void isModifyFile(String propertiesName){
File file = new File(PATH+propertiesName);
String timeKey = new StringBuffer(propertiesName).append("time").toString();
//最后一次修改时间戳
long lastTime = propertiesMap.get(timeKey)==null?0:(long) propertiesMap.get(timeKey);
//上次修改时间戳
long curTime = file.lastModified();
if(lastTime != curTime){
//读取配置文件
readFile(file,propertiesName);
log.info("读取配置信息,文件重新加载.file:{};上次修改时间戳:{},最后一次修改时间戳:{}",propertiesName,curTime,lastTime);
}
}
/**
* 读取配置文件信息
* @param file
* @param propertiesName
*/
public static void readFile(File file,String propertiesName){
try {
Properties properties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(file));
propertiesMap.put(propertiesName,properties);
propertiesMap.put(new StringBuffer(propertiesName).append("time").toString(),file.lastModified());
} catch (IOException e) {
e.printStackTrace();
}
}
}