Apache Commons configuration使用入門


使用Commons  Configuration可以很好的管理我們的配置文件的讀寫,

官網:http://commons.apache.org/configuration

需要用到commons-lang,commons-collections,commons-logging,log4j jar包

public class Test {
    
    public static  void main(String[] args) throws ConfigurationException, InterruptedException {
        xmlLoadTest();
        fileLoadTest();
        saveTest();
        runtimeReload();
    }

    //xml文件
    public static void xmlLoadTest() throws ConfigurationException{
        String file = "test1.xml";
        XMLConfiguration config = new XMLConfiguration(Test.class.getResource(file));
        System.out.println(config.getString("conf.url"));
        System.out.println(config.getDouble("conf.money"));
    }
  
    //properties文件
    private static void fileLoadTest() throws ConfigurationException {
        String file = "test2.properties";
        PropertiesConfiguration config = new PropertiesConfiguration(Test.class.getResource(file));
        System.out.println(config.getString("url"));
    }

    //保存到文件
    public static void saveTest() throws ConfigurationException{
        String file = "test2.properties";
        PropertiesConfiguration config = new PropertiesConfiguration(Test.class.getResource(file));
        //設置自動保存 或顯示調用 config.save();
        config.setProperty("colors.background", "#000000");
        config.setAutoSave(true);
    }

    //運行期參數修改加載
    public static void runtimeReload() throws ConfigurationException, InterruptedException{
        String file = "test2.properties";
        PropertiesConfiguration config = new PropertiesConfiguration(Test.class.getResource(file));
        config.setReloadingStrategy(new FileChangedReloadingStrategy());
        System.out.println(config.getString("url"));
        Thread.sleep(10000);//在休眠期間,手動修改文件里面的url值后觀察日志情況
        System.out.println(config.getString("url"));
    }

}

版權聲明:本文為博主原創文章,未經博主允許不得轉載。


免責聲明!

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



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