import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
public class Property {
private static final Logger logger = LoggerFactory.getLogger(Property.class);
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
// 取出application.properties文件参数
InputStream ins = Property.class.getClassLoader().getResourceAsStream("application.properties");
Properties propss = new Properties();
propss.load(ins);
String active = propss.getProperty("spring.profiles.active");
StringBuilder propertiesName = new StringBuilder("application-").append(active).append(".properties");
in = Property.class.getClassLoader().getResourceAsStream(propertiesName.toString());
props.load(in);
//转码处理
Set<Object> keyset = props.keySet();
Iterator<Object> iter = keyset.iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
String newValue = null;
//属性配置文件自身的编码
String propertiesFileEncode = "utf-8";
newValue = new String(props.getProperty(key).getBytes("ISO-8859-1"), propertiesFileEncode);
props.setProperty(key, newValue);
}
} catch (Exception e) {
logger.error("加载异常:"+e.toString());
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("spark.properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}