加載properties 代碼

package com.common.utils;java

//import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;apache

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;json

/**
 * Created by  on 2018/4/4.
 */
public class ConfigUtil {spa

    private static ConcurrentHashMap propertiesMap = new ConcurrentHashMap();.net

    private static final String CORE_PROPERTIES_FILE = "context-ilife_core.properties";get

    private static Log log = LogFactory.getLog(ConfigUtil.class);io

    /**
     * 從指定properties文件加載配置
     * @param fileName
     * @return
     */
    public static Properties loadProperties(String fileName) {
        Properties configs;
        if(propertiesMap.get(fileName)==null) {
            synchronized (propertiesMap) {
                if(propertiesMap.get(fileName)==null) {
                    InputStream configFile = ConfigUtil.class.getClassLoader().getResourceAsStream(fileName);
                    configs = new Properties();ast

                    try {
                        configs.load(configFile);
//            log.info("configs:"+ JSONObject.toJSONString(configs));
                    } catch (Exception e) {
                        log.error("Classpath下沒有找到配置文件 " + fileName, e);
                    } finally {
                        try {
                            if (configFile != null) {
                                configFile.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }class

                    propertiesMap.put(fileName, configs);
                }
            }
        }
        configs = (Properties) propertiesMap.get(fileName);
        return configs;
    }import

    /**
     * 從指定properties文件讀取配置
     * @param fileName
     * @param propertyName
     * @return
     */
    public static String getProperty(String fileName, String propertyName){
        Properties configs = loadProperties(fileName);
        if(configs!=null)
            return configs.getProperty(propertyName);
        else
            return null;
    }

    /**      * 從context-ilife_core.properties文件讀取配置      * @param propertyName      * @return      */     public static String getProperty(String propertyName){         return getProperty(CORE_PROPERTIES_FILE, propertyName);     } }  

相關文章
相關標籤/搜索