目錄結構:
1. 首先有個一主配置文件:custom.properties,主要用於加載全局的,不區分開發環境的配置,里面必須包含一個屬性profiles.active(區分加載哪個配置);
2. 創建一個 custom-xxx.properties 的配置文件,在主配置文件中設置 profiles.active=xxx 即可加載 custom-xxx.properties 的配置,主要用於區分開發環境;
3. Tools.isBlank() 方法可看 https://www.cnblogs.com/lixingwu/p/7113591.html ;
4. 使用方法可查看main方法。
package com.zhwlt.logistics.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 讀取properties文件 * * @author lixingwu */ 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 (!Tools.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 (Tools.isBlank(val)) { val = propertiesCustom.getProperty(name); } return val; } public static void main(String[] args) { PropertiesUtils pro = PropertiesUtils.getInstance(); String value = pro.getProperty("custom.properties.name"); System.out.println(value); } }