apache commons-configuration包讀取配置文件


1、pom依賴添加

<!-- 配置文件讀取 -->
<dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>1.10</version>
</dependency>

2、讀取.properties文件

使用PropertiesConfiguration配置類,主要示例代碼如下:

public static final String fileName = "test.properties";
public static PropertiesConfiguration cfg = null;

    static {
        try {
            cfg = new PropertiesConfiguration(fileName);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        // 當文件的內容發生改變時,配置對象也會刷新
        cfg.setReloadingStrategy(new FileChangedReloadingStrategy());
    }

    /**
     * 讀String
     * @param key
     * @return
     */
    public static String getStringValue(String key) {
        return cfg.getString(key);
    }

    /**
     * 讀int
      * @param key
     * @return
     */
    public static int getIntValue(String key) {
        return cfg.getInt(key);
    }

    /**
     * 讀boolean
      * @param key
     * @return
     */
    public static boolean getBooleanValue(String key) {
      return cfg.getBoolean(key);
    }
    /**
     * 讀List
     */
    public static List<?> getListValue(String key) {
        return cfg.getList(key);
    }
    /**
     * 讀數組
     */
    public static String[] getArrayValue(String key) {
        return cfg.getStringArray(key);
    }

test.properties可以如下定義:

name=king
port=21
flag=true
interest=guitar,piano

之后就可以用給定的一些讀取方法操作了

String name = CGPropetiesUtil.getStringValue("name");
System.out.println("String:" + name);

3、讀取.xml文件

使用XMLConfiguration配置類

主要代碼

  public static final String fileName = "test.xml";

    public static XMLConfiguration cfg = null;

    static {
        try {
            cfg = new XMLConfiguration(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 配置文件 發生變化就重新加載
        cfg.setReloadingStrategy(new FileChangedReloadingStrategy());
    }

    public static String getStringValue(String key) {
        return cfg.getString(key);
    }

    public static int getIntValue(String key) {
        return cfg.getInt(key);
    }

test.xml定義如下:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <database>
        <url>127.0.0.1</url>
        <port>1521</port>
        <login>admin</login>
        <password>admin</password>
    </database>
</config>

測試操作同上。

4、對於一個文件來說,他的操作就對應一個配置類,而不能使用同一個配置類操作多個文件,否則它只以讀取的第一個為操作對象。針對這種情況,可以寫成一個通用的讀取工具,簡單示例如下:

public class CGCommonUtil {

    /**
     * 一個文件對應一個Configuration
     */
    public static Map<String, Configuration> configMap = new ConcurrentHashMap<String, Configuration>();

    /**
     * 文件后綴
     */
    private static final String SUFFIX_PROPERTIES = ".properties";
    private static final String SUFFIX_XML = ".xml";

    public static Configuration getConfig(String fileName) {
        if (!configMap.containsKey(fileName)) {
            CGCommonUtil.initConfig(fileName);
        }

        Configuration cfg = configMap.get(fileName);
        if (null == cfg) {
            throw new IllegalArgumentException("cfg is null");
        }

        return cfg;
    }

    private static void initConfig(String fileName) {
        Configuration cfg = null;
        try {
            if (fileName.endsWith(SUFFIX_XML)) {
                cfg = new XMLConfiguration(fileName);
            } else if (fileName.endsWith(SUFFIX_PROPERTIES)) {
                cfg = new PropertiesConfiguration(fileName);
            }
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        if (null != cfg) {
            configMap.put(fileName, cfg);
        } else {
            System.out.println("cfg is null");
        }
    }

    /**
     * 讀String
     * @param key
     * @return
     */
    public static String getStringValue(Configuration cfg, String key) {
        return cfg.getString(key);
    }

    /**
     * 讀int
     * @param key
     * @return
     */
    public static int getIntValue(Configuration cfg, String key) {
        return cfg.getInt(key);
    }

    /**
     * 讀boolean
     * @param key
     * @return
     */
    public static boolean getBooleanValue(Configuration cfg, String key) {
        return cfg.getBoolean(key);
    }
    /**
     * 讀List
     */
    public static List<?> getListValue(Configuration cfg, String key) {
        return cfg.getList(key);
    }
    /**
     * 讀數組
     */
    public static String[] getArrayValue(Configuration cfg, String key) {
        return cfg.getStringArray(key);
    }

    public static void main(String[] args) {
        Configuration config = getConfig("test.properties");
        String name1 = getStringValue(config, "name");
    }
}

以上可以作為一個通用的讀取工具,為每一個文件都設置了一個相應的配置操作類,如果考慮本地緩存影響會影響內存的話可以考慮定時刪除緩存數據操作

5、Configuration讀取文件源原

入口類ConfigurationUtils

主要涉及的方法如下:

locateFromClasspath方法

static URL locateFromClasspath(String resourceName) {
    URL url = null;
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader != null) {
        url = loader.getResource(resourceName);
        if (url != null) {
            LOG.debug("Loading configuration from the context classpath (" + resourceName + ")");
        }
    }

    if (url == null) {
        url = ClassLoader.getSystemResource(resourceName);
        if (url != null) {
            LOG.debug("Loading configuration from the system classpath (" + resourceName + ")");
        }
    }

    return url;
}

首先它通過獲取了當前線程的一個類加載器,通過加載器的getResouce方法去類加載器找到resourceName這個文件

getResouce方法

public URL getResource(String name) {
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = getBootstrapResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}

先去父節點的loader去加載資源文件,如果找不到,則會去BootstrapLoader中去找,如果還是找不到,才調用當前類的classLoader去找。這也就是JDK類加載的雙親委派模型。

getInputStream方法

public InputStream getInputStream(URL url) throws ConfigurationException {
    File file = ConfigurationUtils.fileFromURL(url);
    if (file != null && file.isDirectory()) {
        throw new ConfigurationException("Cannot load a configuration from a directory");
    } else {
        try {
            return url.openStream();
        } catch (Exception var4) {
            throw new ConfigurationException("Unable to load the configuration from the URL " + url, var4);
        }
    }
}

調用url的openStream()方法去獲得此文件的輸入流

 

GItHub源碼參照

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM