1:普通变量的属性变量加载
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @ClassName PropertyLoader
* @Description 属性配置文件加载类 - 非单例、非线程安全, 在需要的地方创建一个
* @author weiw
* @date 2018年5月15日
*
*/
public class PropertyLoader {
private static final Logger logger = LoggerFactory.getLogger(PropertyLoader.class);
private Properties configuration = null;
public PropertyLoader(String configPath) {
configuration = load(configPath);
}
private Properties load(String configPath) {
Properties prop = null;
if (StringUtils.isBlank(configPath)) {
throw new IllegalArgumentException("配置文件路径不能为空!configPath=".concat(configPath));
}
try {
InputStream is = PropertyLoader.class.getClassLoader().getResourceAsStream(configPath);
prop = new Properties();
prop.load(is);
is.close();
logger.info("Loading {} success.", configPath);
} catch (Exception e) {
logger.error("Loading {} failed. error:{}", configPath, e);
}
return prop;
}
public String getValue(String key) {
return this.configuration.getProperty(key);
}
public int getIntValue(String key) {
String valueStr = this.configuration.getProperty(key);
try {
return Integer.parseInt(valueStr);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return -1;
}
public int getIntValue(String key, int defaultValue) {
String valueStr = this.configuration.getProperty(key);
if (StringUtils.isEmpty(valueStr))
return defaultValue;
try {
return Integer.parseInt(valueStr);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return defaultValue;
}
public double getDoubleValue(String key) {
String valueStr = this.configuration.getProperty(key);
try {
return Double.parseDouble(valueStr);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return -1.0D;
}
public long getLongValue(String key) {
String valueStr = this.configuration.getProperty(key);
try {
return Long.parseLong(valueStr);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return -1L;
}
2:加载静态变量配置,引用PropertyLoader
}
/**
* @ClassName LoadStaticProperties
* @Description 初始化配置的静态常量
* @author weiw
* @date 2018年6月25日
*
*/
public class LoadStaticProperties {
private static final Logger logger = LoggerFactory.getLogger(LoadStaticProperties.class);
private static final PropertyLoader CONFIGER =new PropertyLoader("/config/imgUtils.properties");
private static final String fastDfsHost;
private static final String accessKeyID;
private static final String accessKeySecret;
/** 初始化静态变量 **/
static {
fastDfsHost = CONFIGER.getValue("imageUtil.fast.DfsHost");
accessKeyID = CONFIGER.getValue("imageUtil.accessKeyID");
accessKeySecret = CONFIGER.getValue("imageUtil.accessKeySecret");
logger.info("fastDfsHost:{}", fastDfsHost);
logger.info("accessKeyID:{}", accessKeyID);
logger.info("accessKeySecret:{}", accessKeySecret);
}
}