commons-Configuration解析XML或者Properties

来源:互联网 发布:实用安卓pp推荐知乎 编辑:程序博客网 时间:2024/05/19 10:12

强大的配置文件解析器Commons-Configuration

Commons Configuration是一个java应用程序的配置文件管理工具。可以从properties或者xml文件中加载软件的配置信息,用来构建支撑软件运行的基础环境。在一些配置文件较多较的复杂的情况下,使用该配置工具比较可以简化配置文件的解析和管理。也提高了开发效率和软件的可维护性。


一、解析属性配置文件

 使用org.apache.commons.configuration包中的PropertiesConfiguration类装载一个属性文件后,可以提供对于number、arrays、list的访问,下面的例子包括了3个属性,speed 是一个浮点数NUMBER,name是一个用逗号分隔的字符列表,Correct是一个布尔类型。

speed=23.332
names=Bob,Gautam,Jarret,Stefan
correct=false

 这个名字为test.properties的属性文件存储在一个应用的工作目录中,现在需要以上面说过的float, List, andboolean方式访问3个属性,以面的代码建了一个PropertiesConfiguration对象,可以访问每个属性。

Java代码 :
  1. import org.apache.commons.configuration.Configuration; 
  2.  
  3. import org.apache.commons.configuration.PropertiesConfiguration; 
  4.  
  5. Configuration config = new PropertiesConfiguration( "test.properties" ); 
  6.  
  7.  
  8. float speed = config.getFloat("speed")); 
  9.  
  10. List names = config.getList("names")); 
  11.  
  12. boolean correct = config.getBoolean("correct"); 
二、 解析XML配置文件
<?xml version="1.0" encoding="UTF-8" ?>

<books>
<book>
<name>spring</name>
<price>25.6</price>
<author sex="m">lichun</author>
<author sex="f">geyang</author>
</book>
<book>
<name>hibernate</name>
<price>25.7</price>
</book>
<book>
<name>struts</name>
<price>25.8</price>
</book>
</books>


java代码:

 String filePath="appConfig.xml";

 

try {
XMLConfiguration config=new XMLConfiguration(filePath);

System.out.println("load file "+filePath+" success.");
 

Iterator<String> itr=config.getKeys(); //获取当前XMLConfiguration对象可以使用的key
while(itr.hasNext()){
System.out.println(itr.next());
}


String bookname=config.getString("book(2).name"); //获取第三个book元素的名字
double price=config.getDouble("book.price"); //获取第一个book元素的price的值
 List authors=config.getList("book.author"); //获取第一个book元素的authors列表
String sex=config.getString("book.author(1)[@sex]"); //获取第一个book元素的第二个author元素的属性sex的值

三、加载多个配置文件:

 1)使用CompositeConfiguration 加载多个配置文件

 XMLConfiguration config=new XMLConfiguration(filePath);
 Configuration propConfig = new PropertiesConfiguration( "test.properties" ); 


 CompositeConfiguration cpConfig=new CompositeConfiguration();

 cpConfig.addConfiguration(new SystemConfiguration());//加载系统属性
 cpConfig.addConfiguration(config); //加载xml属性

 cpConfig.addConfiguration(propConfig); //加载property文件属性

 cpConfig.getString("book.author"); //获取属性的值

注意:加载多个配置文件时,同名属性最终的值与addConfiguration的顺序有关,cpConfig会先取第一个配置对象(在这里是SystemConfiguration对象)中包含的值,如果有,不再继续查找;否则再按顺序到下一个配置对象(在这里是XMLConfiguration对象)中查找,找不到的话再依此类推

 2)使用ConfigurationFactory加载多个配置文件

 先建立一个configuration的工厂配置文件configFactory.xml,内容如下:

 <?xml version="1.0" encoding="UTF-8" ?>

 <configuration>
 <system/>
 <xml fileName="appConfig.xml"/>
 <properties fileName="test.properties"/>
 </configuration>

 再使用如下代码加载该配置文件即可:

 ConfigurationFactory factory = new ConfigurationFactory("config.xml");

0 0