1. 程式人生 > >java初始化配置檔案, 直接使用PropUtil.get(key)獲取值

java初始化配置檔案, 直接使用PropUtil.get(key)獲取值

package com.audaque.cas.server;


import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
import java.io.*;  
import java.nio.charset.StandardCharsets;  
import java.util.Properties;  
import java.util.regex.Pattern;  
  
/** 
 * 配置檔案工具類 
 * 
 * @author Luo Yong 
 * @date 2014-03-12 
 */  
public final class PropUtil {  
  
    private static final Logger LOG = LoggerFactory.getLogger(PropUtil.class.getName());  
    /** FIXME 找副檔名為properties的檔案*/  
    private static final String REGEX_PROPERTIES = "^(.*).properties$";  
    /** 查詢檔案的匹配正則*/  
    private static final Pattern PATTERN_PROPERTIES = Pattern.compile(REGEX_PROPERTIES);  
    private static Properties properties = new Properties();  
    private static ClassLoader classLoader = getDefaultClassLoader();  
  
    static {  
        init();  
    }  
  
    /** 
     * 獲取配置檔案 
     * 
     * @param key 
     * @return 
     */  
    public static String get(final String key) {  
        return getProperties().getProperty(key);  
    }  
  
    /** 
     * 獲取配置檔案,為空時,返回預設值 
     * 
     * @param key 
     * @param defaultValue 
     * @return 
     */  
    public static String get(final String key, final String defaultValue) {  
        String value = getProperties().getProperty(key);  
        if (value == null || value.trim().isEmpty()) {  
            return defaultValue;  
        }  
        return value;  
    }  
  
    private static Properties getProperties() {  
        return properties;  
    }  
  
    /** 
     * 初始化配置檔案 
     */  
    private static void init() {  
        // 獲取classpath  
        String classpath = getClasspath();  
        if (classpath != null) {  
            // 從classpath的父節點開始查詢  
            File baseDir = new File(classpath).getParentFile();  
            loadDir(baseDir);  
        }  
    }  
  
    /** 
     * 獲取classpath 
     */  
    private static String getClasspath() {  
        String classpath = null;  
        try {  
            classpath = classLoader.getResource("/").getPath();  
        } catch (Exception e) {  
            try {  
                classpath = classLoader.getResource("").getPath();  
            } catch (Exception ex) {  
                LOG.error(" classpath 初始化失敗:", ex);  
            }  
        }  
        return classpath;  
    }  
  
    /** 
     * copy from org.springframework.util.ClassUtils 
     */  
    private static ClassLoader getDefaultClassLoader() {  
        ClassLoader cl = null;  
        try {  
            cl = Thread.currentThread().getContextClassLoader();  
        } catch (Exception ex) {  
            LOG.error(" Thread.currentThread() 獲取 ClassLoader 出錯:", ex);  
        }  
        if (cl == null) {  
            cl = PropUtil.class.getClassLoader();  
            if (cl == null) {  
                try {  
                    cl = ClassLoader.getSystemClassLoader();  
                } catch (Exception ex) {  
                    LOG.error(" ClassLoader.getSystemClassLoader() 獲取 ClassLoader 出錯:", ex);  
                }  
            }  
        }  
        return cl;  
    }  
  
    /** 
     * 遞迴查詢配置檔案<br/> 
     * 
     * @param baseDir 查詢的資料夾 
     */  
    private static void loadDir(File baseDir) {  
        // 判斷目錄是否存在  
        if (!baseDir.exists() || !baseDir.isDirectory()) {  
            return;  
        }  
        String tempPath;  
        File[] files = baseDir.listFiles();  
        for (File file : files) {  
            if (file.isFile()) {  
                tempPath = file.getAbsolutePath();  
                if (PATTERN_PROPERTIES.matcher(tempPath).matches()) {  
                    // 匹配成功,將檔案路徑新增到結果集  
                    load(file);  
                }  
            } else if (file.isDirectory()) {  
                loadDir(file);  
            }  
        }  
    }  
  
    /** 
     * 讀取配置檔案 
     * 
     * @param file 
     */  
    private static void load(File file) {  
        try (InputStream is = new FileInputStream(file);  
             InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) {  
            getProperties().load(isr);  
        } catch (IOException e) {  
            throw new RuntimeException("讀取配置檔案" + file.getName() + "出現異常", e);  
        }  
    }  
  
    /** 
     * 通過配置檔案路徑和名稱,熱載入Properties 
     */  
    public static void load(String propsName) {  
        try (InputStream is = classLoader.getResourceAsStream(propsName)) {  
            getProperties().load(is);  
        } catch (IOException e) {  
            throw new RuntimeException("讀取配置檔案" + propsName + "出現異常", e);  
        }  
    }  
  
    private PropUtil() {  
    }  
}