代碼動態讀取配置文件屬性

代碼動態讀取配置文件屬性

一: 使用ResourceBundle來讀取(jdk提供的)

ResourceBundle類是java自帶的類用來讀取項目中後綴爲properties的配置文件。(只能讀取.properties文件)

配置文件名稱:xxxx.properties(可將文件存放在工程的resource目錄下,或者lib目錄下)

示例:

配置文件準備: test1.properties , test2.properties ,test3.properties

name=張韶涵
# 其他2個配置文件內容差不多 省略...

動態讀取配置文件工具類:

/**
 * @Author: zhihao
 * @Date: 25/2/2020 下午 2:30
 * @Description: ResourceBundle獲取配置文件屬性工具類
 * @Versions 1.0
 **/
public class Config2Properties {

    private static Logger log = LoggerFactory.getLogger(Config2Properties.class);
    /**
     * ResourceBundle 只能讀取後綴名爲properties配置文件, 並且路徑不用寫後綴名
     */
    private static ResourceBundle test1 = ResourceBundle.getBundle("pay/test1");

    private static ResourceBundle test2 = ResourceBundle.getBundle("test2");

    private static ResourceBundle test3 = ResourceBundle.getBundle("test3");

    /**
     * 獲取test1配置文件屬性
     *
     * @param key 鍵
     * @return java.lang.String 讀取不到返回null
     * @author: zhihao
     * @date: 25/2/2020
     */
    public static String getTest1Config(String key) {
        String value = null;
        try {
            //如果讀取到配置文件沒有的key會報異常
            value = test1.getString(key);
        } catch (MissingResourceException e) {
            log.error(e.getMessage(), e);
        }
        return value;
    }

    public static String getTest2Config(String key) {
        String value = null;
        try {
            value = test2.getString(key);
        } catch (MissingResourceException e) {
            log.error(e.getMessage(), e);
        }
        return value;
    }

    public static String getTest3Config(String key) {
        String value = null;
        try {
            value = test3.getString(key);
        } catch (MissingResourceException e) {
            log.error(e.getMessage(), e);
        }
        return value;
    }
}

二: 使用Properties來讀取(jdk提供的) (推薦使用)

示例:

/**
 * @Author: zhihao
 * @Date: 25/2/2020 下午 2:30
 * @Description: Properties獲取配置文件屬性工具類
 * @Versions 1.0
 **/
public class ConfigProperties {

    private static Logger log = LoggerFactory.getLogger(ConfigProperties.class);

    private Properties properties = new Properties();

    /**
     * 加載配置文件
     *
     * @param resourcesPath 配置文件路徑
     * @return
     * @author: zhihao
     * @date: 25/2/2020
     * {@link #}
     */
    public ConfigProperties(String... resourcesPath) {
        this.loadProperties(resourcesPath);
    }

    /**
     * 獲取配置文件屬性,獲取不到返回null
     *
     * @param key 鍵
     * @return java.lang.String
     * @author: zhihao
     * @date: 25/2/2020
     */
    public String getConfigValue(String key) {
        String value = properties.getProperty(key);
        return value;
    }

    /***
     * 批量加載配置文件 相同key會覆蓋
     *
     * @param resourcesPath 配置文件路徑
     * @return void
     * @author: zhihao
     * @date: 25/2/2020
     * {@link #}
     */
    private Properties loadProperties(String... resourcesPath) {
        if (resourcesPath.length > 0) {
            for (String property : resourcesPath) {
                InputStream is = this.getClass().getClassLoader().getResourceAsStream(property);
                try {
                    properties.load(is);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    IoUtil.close(is);
                }
            }
            return properties;
        }
        return null;
    }
}

三: 使用spring框架提供的工具包讀取

工具類:

package com.zhihao.util;

import cn.hutool.core.io.IoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;

/**
 * Properties文件載入工具類. 可載入多個properties文件, 相同的屬性在最後載入的文件中的值將會覆蓋之前的值,但以System的Property優先.
 */
public class PropertiesLoader {

    private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);

    private static ResourceLoader resourceLoader = new DefaultResourceLoader();

    private final Properties properties;

    public PropertiesLoader(String... resourcesPaths) {
        properties = loadProperties(resourcesPaths);
    }

    public Properties getProperties() {
        return properties;
    }

    /**
     * 取出Property,但以System的Property優先,取不到返回空字符串.
     */
    private String getValue(String key) {
        String systemProperty = System.getProperty(key);
        if (systemProperty != null) {
            return systemProperty;
        }
        if (properties.containsKey(key)) {
            return properties.getProperty(key);
        }
        return "";
    }

    /**
     * 取出String類型的Property,但以System的Property優先,如果都爲Null則拋出異常.
     */
    public String getProperty(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return value;
    }

    /**
     * 取出String類型的Property,但以System的Property優先.如果都爲Null則返回Default值.
     */
    public String getProperty(String key, String defaultValue) {
        String value = getValue(key);
        return value != null ? value : defaultValue;
    }

    /**
     * 取出Integer類型的Property,但以System的Property優先.如果都爲Null或內容錯誤則拋出異常.
     */
    public Integer getInteger(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Integer.valueOf(value);
    }

    /**
     * 取出Integer類型的Property,但以System的Property優先.如果都爲Null則返回Default值,如果內容錯誤則拋出異常
     */
    public Integer getInteger(String key, Integer defaultValue) {
        String value = getValue(key);
        return value != null ? Integer.valueOf(value) : defaultValue;
    }

    /**
     * 取出Double類型的Property,但以System的Property優先.如果都爲Null或內容錯誤則拋出異常.
     */
    public Double getDouble(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Double.valueOf(value);
    }

    /**
     * 取出Double類型的Property,但以System的Property優先.如果都爲Null則返回Default值,如果內容錯誤則拋出異常
     */
    public Double getDouble(String key, Integer defaultValue) {
        String value = getValue(key);
        return value != null ? Double.valueOf(value) : defaultValue;
    }

    /**
     * 取出Boolean類型的Property,但以System的Property優先.如果都爲Null拋出異常,如果內容不是true/false則返回false.
     */
    public Boolean getBoolean(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Boolean.valueOf(value);
    }

    /**
     * 取出Boolean類型的Property,但以System的Property優先.如果都爲Null則返回Default值,如果內容不爲true/false則返回false.
     */
    public Boolean getBoolean(String key, boolean defaultValue) {
        String value = getValue(key);
        return value != null ? Boolean.valueOf(value) : defaultValue;
    }

    /**
     * 載入多個文件, 文件路徑使用Spring Resource格式.
     */
    private Properties loadProperties(String... resourcesPaths) {
        Properties props = new Properties();

        for (String location : resourcesPaths) {

//			logger.debug("Loading properties file from:" + location);

            InputStream is = null;
            try {
                Resource resource = resourceLoader.getResource(location);
                is = resource.getInputStream();
                props.load(is);
            } catch (IOException ex) {
                logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());
            } finally {
                IoUtil.close(is);
            }
        }
        return props;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章