public final class PropertiesUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);
/**
* 加载Properties属性文件
*
* @param propFilePath Properties属性文件相对classpath的路径
* @param encode Properties属性文件编码
* @return Properties对象
*/
public static Properties loadProperties(String propFilePath, String encode) {
if (StringUtils.isBlank(propFilePath)) {
return null;
}
Properties prop = null;
InputStream in = null;
try {
in = PropertiesUtil.class.getResourceAsStream(propFilePath);//path 不以’/'开头时
默认是从此类所在的包下取资源,以’/'开头则是从
//ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
prop = loadProperties(in, encode);
} catch (Exception e) {
prop = null;
LOGGER.error("loadProperties - Excp : {}; propFilePath = {}", e, propFilePath);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
return prop;
}
/**
* 加载Properties属性文件
*
* @param in Properties属性文件输入流
* @param encode Properties属性文件编码
* @return Properties对象
*/
public static Properties loadProperties(InputStream in, String encode) {
if (in == null) {
return null;
}
if (StringUtils.isBlank(encode)) {
encode = Constant.Encode.DEFAULT;
}
Properties prop = new Properties();
Reader reader = null;
try {
reader = new InputStreamReader(in, encode);
prop.load(reader);
} catch (Exception e) {
prop = null;
LOGGER.error("loadProperties - Excp : {}", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return prop;
}
}
public final class ConfigUtil {
private static final String SYSTEM_CONFIG_PATH = "/config.properties";
private static final Properties SYSTEM_CONFIG_PROP;
private String dbUser=null;
private String dbPwd=null;
private String url=null;
static {
SYSTEM_CONFIG_PROP = PropertiesUtil.loadProperties(SYSTEM_CONFIG_PATH,
Constant.Encode.UTF_8);//Constant.Encode.UTF_8已在接口中自定义编码格式
}
/*interface Encode {
String UTF_8 = "UTF-8";
String GBK = "GBK";
String ISO_8859_1 = "ISO-8859-1";
String DEFAULT = UTF_8;
}*/
/**
* 获取系统配置的值,即配置文件:/configs/system_config.properties
*
* @param key
* @return
*/
public static String getSystemConfig(String key) {
return SYSTEM_CONFIG_PROP == null ? null : SYSTEM_CONFIG_PROP.getProperty(key);
}
/**
* 无参构造方法
*/
public MysqlImpl(){
this.url= ConfigUtil.getSystemConfig("mysql.jdbc.url");
this.dbUser=ConfigUtil.getSystemConfig("mysql.jdbc.username");
this.dbPwd=ConfigUtil.getSystemConfig("mysql.jdbc.password");
new MysqlImpl(this.url,this.dbUser,this.dbPwd);
}
}
public class MysqlImpl {
private String dbUser=null;
private String dbPwd=null;
private String url=null;
/**
* 无参构造方法
*/
public MysqlImpl(){
this.url= ConfigUtil.getSystemConfig("mysql.jdbc.url");
this.dbUser=ConfigUtil.getSystemConfig("mysql.jdbc.username");
this.dbPwd=ConfigUtil.getSystemConfig("mysql.jdbc.password");
new MysqlImpl(this.url,this.dbUser,this.dbPwd);
}
}