Commons Configuration是一个java应用程序的配置管理工具。可以从properties或者xml文件中加载软件的配置信息,用来构建支撑软件运行的基础环境。在一些配置文件较多较的复杂的情况下,使用该配置工具比较可以简化配置文件的解析和管理。也提高了开发效率和软件的可维护性。
一、介绍
官方列举Commons Configuration的主要功能:
Configuration parameters may be loaded from the following sources:
Properties files
XML documents
Windows INI files
Property list files (plist)
JNDI
JDBC Datasource
System properties
Applet parameters
Servlet parameters
Commons Configuration所依赖的包
Component | Dependencies |
---|---|
Core | Java 1.3 commons-collections commons-lang commons-logging |
ConfigurationFactory | commons-digester commons-beanutils Java 1.4 or xml-apis |
DefaultConfigurationBuilder | commons-beanutils Java 1.4 or (xml-apis + xerces + xalan) |
DatabaseConfiguration | JDBC 3.0 (Java 1.4 or jdbc2_0-stdext.jar) |
XMLConfiguration | Java 1.4 or (xml-apis + xerces + xalan) |
XMLPropertiesConfiguration | Java 1.4 or (xml-apis + xerces) |
PropertyListConfiguration | commons-codec |
XMLPropertyListConfiguration | commons-codec Java 1.4 or xml-apis |
ConfigurationDynaBean | commons-beanutils |
XPathExpressionEngine | commons-jxpath |
EnvironmentConfiguration | Java 1.5 or ant 1.6.5 |
二、给出一个简单的例子
package cfgtest;
import org.apache.commons.configuration.*;
/**
* Commons Configuration读取属性文件的例子
*
* @author leizhimin 2008-9-23 9:40:17
*/
public class Test1 {
public static void main(String[] args) throws ConfigurationException {
test1();
}
public static void test1() throws ConfigurationException {
CompositeConfiguration config = new CompositeConfiguration();
//config.addConfiguration( new SystemConfiguration());
config.addConfiguration( new PropertiesConfiguration( "cfgtest/test1.properties"));
String usernaem = config.getString( "username");
String password = config.getString( "password");
System.out.println(usernaem + " " + password);
}
}
import org.apache.commons.configuration.*;
/**
* Commons Configuration读取属性文件的例子
*
* @author leizhimin 2008-9-23 9:40:17
*/
public class Test1 {
public static void main(String[] args) throws ConfigurationException {
test1();
}
public static void test1() throws ConfigurationException {
CompositeConfiguration config = new CompositeConfiguration();
//config.addConfiguration( new SystemConfiguration());
config.addConfiguration( new PropertiesConfiguration( "cfgtest/test1.properties"));
String usernaem = config.getString( "username");
String password = config.getString( "password");
System.out.println(usernaem + " " + password);
}
}
cfgtest/test1.properties
username = lavasoft
password = leizhimin
password = leizhimin
运行结果:
lavasoft leizhimin
Process finished with exit code 0
Process finished with exit code 0
从上面看出,使用Apache Commons Configuration来读取配置确实很简单,还可以省很多事情。它不光可以读取properties文件,还可以读取xml,还可以读取xml和properties混合文件等等。
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/101242,如需转载请自行联系原作者