目錄
工具類
PropertiesUtils
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 〈一句話功能簡述〉PropertiesUtils工具類<br>
* 〈功能詳細描述〉依次從主配置文件->啓用配置文件中獲取配置信息
*
* @author 劉斌
* @date 2020/3/2
* @see [相關類/方法](可選)
* @since [產品/模塊版本] (可選)
*/
public class PropertiesUtils {
/**
* 主配置文件
*/
private Properties properties;
/**
* 啓用配置文件
*/
private Properties propertiesCustom;
private static PropertiesUtils propertiesUtils = new PropertiesUtils();
/**
* 私有構造,禁止直接創建
*/
private PropertiesUtils() {
// 讀取配置啓用的配置文件名
properties = new Properties();
propertiesCustom = new Properties();
InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream("custom.properties");
try {
properties.load(in);
// 加載啓用的配置
String property = properties.getProperty("profiles.active");
if (!StringTools.isBlank(property)) {
InputStream cin = PropertiesUtils.class.getClassLoader().getResourceAsStream("custom-" + property + ".properties");
propertiesCustom.load(cin);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 獲取單例
*
* @return PropertiesUtils
*/
public static PropertiesUtils getInstance() {
if (propertiesUtils == null) {
propertiesUtils = new PropertiesUtils();
}
return propertiesUtils;
}
/**
* 根據屬性名讀取值
* 先去主配置查詢,如果查詢不到,就去啓用配置查詢
*
* @param name 名稱
*/
public String getProperty(String name) {
String val = properties.getProperty(name);
if (StringTools.isBlank(val)) {
val = propertiesCustom.getProperty(name);
}
return val;
}
public static void main(String[] args) {
PropertiesUtils pro = PropertiesUtils.getInstance();
String mainProperty = pro.getProperty("custom.properties.main");
System.out.println(mainProperty);
System.out.println("================");
String profileProperty = pro.getProperty("dev.name");
System.out.println(profileProperty);
}
}
配置文件
custom.properties
##主配值文件
custom.properties.main=主配置文件
##啓用的配置文件
profiles.active=dev
custom-dev.properties
dev.name=啓用配置文件
調用結果