`
raymond.chen
  • 浏览: 1437307 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

commons-configuration使用范例

    博客分类:
  • Java
 
阅读更多

1、访问属性文件

PropertiesConfiguration config1 = new PropertiesConfiguration("config.properties");
System.out.println(config1.getString("ip"));
System.out.println(config1.getInt("port"));
System.out.println(config1.getStringArray("keys")); //字符串数组,默认逗号分隔
System.out.println(config1.getList("keys")); //List,默认逗号分隔

config1.setProperty("port", "8088"); //修改属性值
config1.save(); //保存文件
System.out.println(config1.getInt("port"));

 属性文件内容如下:

ip=127.0.0.1
port=8080
keys=k1,k2,k3,k4,k5,中文

 

2、访问xml文件

XMLConfiguration config2 = new XMLConfiguration("config.xml");
config2.setExpressionEngine(new XPathExpressionEngine()); //使用XPath表达式语言

//自动重新加载
FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
strategy.setRefreshDelay(5000); //每隔5000毫秒检查配置文件是否有修改,有则自动重新加载
config2.setReloadingStrategy(strategy);

System.out.println(config2.getString("ip"));
System.out.println(config2.getString("address/city"));
System.out.println(config2.getString("databases/database[name='dev']/url"));

 xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configs>
	<ip>192.168.245.222</ip>
	<port>8080</port>
	<address>
		<province>GuangDong</province>
		<city>LuoDing</city>
	</address>
	<databases>
        <database>
            <name>dev</name>
            <url>127.0.0.1</url>
            <port>1521</port>
            <login>admin</login>
            <password>pass</password>
        </database>
        <database>
            <name>product</name>
            <url>192.168.124.11</url>
            <port>1521</port>
            <login>admin</login>
            <password>123456</password>
        </database>
    </databases>
</configs>

 

3、访问环境变量

EnvironmentConfiguration config3 = new EnvironmentConfiguration();
for(Iterator it=config3.getKeys(); it.hasNext(); ){
	String key = (String)it.next();
	System.out.println(key + "=" + config3.getString(key));
}

 

4、访问系统变量

SystemConfiguration config4 = new SystemConfiguration();
for(Iterator it=config4.getKeys(); it.hasNext(); ){
	String key = (String)it.next();
	System.out.println(key + "=" + config4.getString(key));
}

 

5、组合各种配置

CompositeConfiguration config5 = new CompositeConfiguration();
config5.addConfiguration(new EnvironmentConfiguration());
config5.addConfiguration(new SystemConfiguration());
config5.addConfiguration(new XMLConfiguration("config.xml"));
config5.addConfiguration(new PropertiesConfiguration("config.properties"));
System.out.println(config5.getString("JAVA_HOME"));
System.out.println(config5.getString("user.home"));
System.out.println(config5.getString("address.province"));
System.out.println(config5.getList("keys"));

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics