原文:http://commons.apache.org/proper/commons-configuration/userguide/quick_start.html

Reading a properties file

Configuration information is frequently stored in properties files. Consider the following simple file that defines some properties related to accessing a database. We assume that it is stored as database.properties in the local file system:

database.host = db.acme.com
database.port = 8199
database.user = admin
database.password = ???
database.timeout = 60000

The easiest way to read this file is via the Configurations helper class. This class offers a bunch of convenience methods for creating configuration objects from different sources. For reading a properties file the code looks as follows:

Configurations configs = new Configurations();
try
{
Configuration config = configs.properties(new File("config.properties"));
// access configuration properties
...
}
catch (ConfigurationException cex)
{
// Something went wrong
}

Accessing properties

The Configuration object obtained in the last step can now be used to query the values for the stored configuration properties. For this purpose, numerous get methods for different property types are available. For the properties contained in the example file the following methods can be used:

String dbHost = config.getString("database.host");
int dbPort = config.getInt("database.port");
String dbUser = config.getString("database.user");
String dbPassword = config.getString("database.password", "secret"); // provide a default
long dbTimeout = config.getLong("database.timeout");

Note that the keys passed to the get methods match the keys contained in the properties file. If a key cannot be resolved, the default behavior of a configuration is to return null. (Methods that return a primitive type throw an exception because in this case there is no null value.) It is possible to provide a default value which is used when the key cannot be found.

Reading an XML file

XML is also a suitable format for storing configuration information, especially if the data becomes more complex. For instance, lists of values can be stored in a natural way by just repeating tags. The example file for this section defines some directory paths that are to be processed by an application. It is named paths.xml and looks as follows:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<configuration>
<processing stage="qa">
<paths>
<path>/data/path1</path>
<path>/data/otherpath</path>
<path>/var/log</path>
</paths>
</processing>
</configuration>

Reading this file works analogously to reading a properties file. Again a Configurations instance is needed (by the way, this class is thread-safe, and an instance can be shared and reused to read multiple configuration sources), but this time we use the xml() method rather than properties():

Configurations configs = new Configurations();
try
{
XMLConfiguration config = configs.xml("paths.xml");
// access configuration properties
...
}
catch (ConfigurationException cex)
{
// Something went wrong
}

The xml() method returns an object of type XMLConfiguration. This class implements the Configuration interface, but offers some more functionality to access properties in a more structured manner. The reader may also have noticed that we passed a string to xml() while we used a java.io.File object in the properties example. All these methods come in several overloaded variants allowing the caller to specify the configuration source in different ways: as a file, as a URL, or as a string. In the latter case, the file is searched for in various places, including at an absolute file path, at a relative file path, as a resource in the classpath, or in the current user's home directory.

Accessing properties from XML

Accessing properties in a XML configuration (or any other hierarchical configuration) supports the same query methods as for regular configurations. There are some additional facilities that take the hierarchical nature of these sources into account. The properties in the example configuration can be read in the following way:

String stage = config.getString("processing[@stage]");
List<String> paths = config.getList(String.class, "processing.paths.path");

The keys for properties are generated by concatening the possibly nested tag names in the XML document (ignoring the root element). For attributes, there is a special syntax as shown for thestage property. Because the path element appears multiple times it actually defines a list. With the getList() method all values can be queried at once.

Hierarchical configurations support an advanced syntax for keys that allows a navigation to a specific element in the source document. This is achieved by adding numeric indices in parentheses after the single key parts. For instance, in order to reference the second path element in the list, the following key can be used (indices are 0-based):

String secondPath = config.getString("processing.paths.path(1)");

For elements which are not repeated such indices can be dropped. It is also possible to set an alternative expression engine - the component that evaluates and interprets configuration keys. There is an implementation available which can deal with XPath expressions. Refer to Expression engines for further details.

Updating a configuration

The Configuration interface defines some methods for manipulating configuration properties. Typical CRUD operations are available for all properties. The following code fragment shows how the example properties configuration can be changed. The port of the database is changed to a new value, and a new property is added:

config.setProperty("database.port", 8200);
config.addProperty("database.type", "production");

addProperty() always adds a new value to the configuration. If the affected key already exists, the value is added to this key, so that it becomes a list. setProperty() in contrast overrides an existing value (or creates a new one if the key does not exist). Both methods can be passed an arbitrary value object. This can also be an array or a collection, which makes it possible to add multiple values in a single step.

Saving a configuration

After a configuration has been manipulated, it should probably be saved again to make the changes persistent. Otherwise, the changes are only in memory. If configurations are to be changed, it is preferrable to obtain them via a different mechanism: a configuration builder. Builders are the most powerful and flexible way to construct configurations. They support many settings that impact the way the configuration data is loaded and the resulting configuration object behaves. Builders for file-based configurations also offer a save() method that writes all configuration data back to disk. Configuration builders are typically created using a fluent API which allows a convenient and flexible configuration of the builder. This API is described in the section Configuration builders. For simple use cases, the Configurations class we have already used has again some convenience methods. The following code fragment shows how a configuration is read via a builder, manipulated, and finally saved again:

Configurations configs = new Configurations();
try
{
// obtain the configuration
FileBasedConfigurationBuilder<XMLConfiguration> builder = configs.xmlBuilder("paths.xml");
XMLConfiguration config = builder.getConfiguration(); // update property
config.addProperty("newProperty", "newValue"); // save configuration
builder.save();
}
catch (ConfigurationException cex)
{
// Something went wrong
}

Commons Configuration2 - Quick start guide的更多相关文章

  1. SlickUpload Quick Start Guide

    Quick Start Guide The SlickUpload quick start demonstrates how to install SlickUpload in a new or ex ...

  2. RF《Quick Start Guide》操作总结

    这篇文章之所以会给整理出来,是因为学了一个季度的RF后,再去看官网的这个文档,感触破多,最大的感触还是觉得自己走了不少弯路,还有些是学习方法上的弯路.在未查看这类官网文档之前,更多的是看其他各种人的博 ...

  3. QUICK START GUIDE

    QUICK START GUIDE This page is a guide aimed at helping anyone set up a cheap radio scanner based on ...

  4. Akka Stream文档翻译:Quick Start Guide: Reactive Tweets

    Quick Start Guide: Reactive Tweets 快速入门指南: Reactive Tweets (reactive tweets 大概可以理解为“响应式推文”,在此可以测试下GF ...

  5. RobotFramework 官方demo Quick Start Guide rst配置文件分析

    RobotFramework官方demo Quick Start Guide rst配置文件分析   by:授客 QQ:1033553122     博客:http://blog.sina.com.c ...

  6. RobotFramework RobotFramework官方demo Quick Start Guide浅析

    RobotFramework官方demo Quick Start Guide浅析   by:授客 QQ:1033553122     博客:http://blog.sina.com.cn/ishouk ...

  7. pax3 quick start guide

    pax3 quick start guide 外观图: 配置:1 * pax3 主机:2 * 吸嘴(一个平的,一个凸的):2 * 底盖(一个烟草的,一个烟膏的):3 * 过滤片:1 * USB充:1 ...

  8. quick start guide for XMEGA ADC

    This is the quick start guide for the Analog to Digital Converter (ADC), with step-by-step instructi ...

  9. [摘录]quarts:Quartz Quick Start Guide

    (Primarily authored by Dafydd James) Welcome to the QuickStart guide for Quartz. As you read this gu ...

随机推荐

  1. 转载JQuery 中empty, remove 和 detach的区别

    转载 http://www.cnblogs.com/lisongy/p/4109420.html .empty()  描述: 从DOM中移除集合中匹配元素的所有子节点. 这个方法不接受任何参数. 这个 ...

  2. 关于TCP主动关闭连接中的wait_timeout

    首先我们先来回顾一下tcp关闭连接的过程: 假设A和B连接状态为EST,A需要主动关闭: A发送FIN给B,并将状态更改为FIN_WAIT1, B接收到FIN将状态更改为CLOSE_WAIT,并回复A ...

  3. iOS UIButton EdgeInsets

    说一下系统的button,image 和 title的位置关系 默认image 和 title的位置关系: 随便画了草图,有点丑,不过不妨碍理解: 第一种:在button上只设置文字,这个时候,but ...

  4. 修改 SVN 账户密码的方法

    记是记不住 的,即便是每天都在用的东西,也有貌似熟悉其实很陌生的时候,或者说根本就是不熟悉.于是需要拿出来经常翻翻,比如我们的SVN账户配置,很简单的一个 case,你可能是svn使用高手,但不一定记 ...

  5. 中国软件开发project师之痛

    在最近的一次会议上,有高层谈到之前在中国觉得自己做得非常牛,但与美国同行接触后却发现与人家存在非常大的差距,这一点我在外企工作时也有过相同的体会.真正与外国同行接触后才会知道什么是差距,在这篇文章中我 ...

  6. C# 函数覆盖总结学习

    覆盖类成员:通过new关键字修饰虚函数表示覆盖该虚函数.一个虚函数被覆盖后,任何父类变量都不能访问该虚函数的具体实现.public virtual void IntroduceMyself(){... ...

  7. ListView 文件重命名

          unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, Control ...

  8. JavaScript与Flash的通信

    当Flash置于HTML容器中时,经常会遇到AS与JS的通信问题,例如:JS能否调用AS中的变量.方法,AS能否调用JS中的变量.方法等等.答案是肯定的.随着技术的不断发展,解决方案也是多种多样的. ...

  9. [Angular 2] Inject Service with "Providers"

    In this lesson, we’re going to take a look at how add a class to the providers property of a compone ...

  10. JAMA:Java矩阵包

    原文链接:JAMA:Java矩阵包 API文档链接:线性代数Java包 JAMA jama是一个非常好用的java的线性代数软件包.适用于日常编程可能碰到的各种矩阵运算问题,提供了一个优雅的简便的解决 ...