原文: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 configurationFileBasedConfigurationBuilder<XMLConfiguration> builder = configs.xmlBuilder("paths.xml");XMLConfiguration config = builder.getConfiguration();// update propertyconfig.addProperty("newProperty", "newValue");// save configuration
    builder.save();
}
catch (ConfigurationException cex)
{// Something went wrong
}

转载于:https://www.cnblogs.com/huey/p/5633543.html

Commons Configuration2 - Quick start guide相关推荐

  1. 【连载】vSphere 4.0 问答之引子 ---《vSphere 4.0 Quick Start Guide》节选和粗译

    这几天来正在细读<vSpherer 4.0 Quick Start Guide>,这确是一本好书啊.谷歌百度了一下,没找到中文版出版,因此萌发了连载一些选节并做部分翻译的念想.我素知自己不 ...

  2. CA AutoSys Workload Automation r11 Quick Resource Guide

    https://supportcontent.ca.com/phpdocs/0/253/253_CA_AutoSys_WA_r11_Guide.pdf Documentation Increase y ...

  3. Leaflet文档阅读笔记-Quick Start Guide笔记

    目录 网络加载JS和CSS 初始化地图 在地图上做标记 在地图上点击事件获得坐标 个人对这篇文档的体会 网络加载JS和CSS 先要加载css,然后在加载js <link rel="st ...

  4. [Cougaar]Cougaar快速开始指导(Cougaar Quick Start Guide)

    [本文翻译自:http://cougaar.org/wp/documentation/cougaar-quick-start-guide/,笔者水平有限,部分内容自知翻译水准不够,仅供学习使用,转载或 ...

  5. Robochameleon——Quick Start Guide

    Robochameleon classes 在这套程序包中有4个基础的类: pwr:表示信号功率 signal_interface:表示信号波形 unit:表示通信系统中的一个元素 module:元素 ...

  6. openldap quick start guide

    openldap 2.4 在centos 7 x64系统上部署 1 下载源码编译 解压 tar -xvf xx ./configure make && make install 2 更 ...

  7. linux下guide编译不了,全志R16编译环境搭建指南,全志R16_Tina SDK Quick Start Guide

    2. Tina SDK 目录结构 ├── tina │ ├── abi │ ├── app │ ├── bionic │ ├── build │ ├── device │ │ ├── softwinn ...

  8. vyos User Guide

    vyos User Guide 来源 https://wiki.vyos.net/wiki/User_Guide The VyOS User Guide is focused on providing ...

  9. 『Java CVE』CVE-2022-33980: Apache Commons Configuration 读文件RCE

    文章目录 影响版本 漏洞原理(机翻自CVE页面) 漏洞复现 环境配置 jdk版本 pom.xml 基本使用demo PoC 代码审计 对生产环境的影响 漏洞修复 参考 完 影响版本 Apache Co ...

最新文章

  1. 触摸心灵-触觉感知和发展的模型
  2. Spring Boot 参考指南(使用NoSQL技术)
  3. opencv mat release thrown_【OpenCV+Python】图像与视频处理入门
  4. 解决The current branch is not configured for pull No value for key branch.master.merge found in config
  5. 1前端学习(2345):关于前端对于xml格式文件的渲染
  6. linux对^M换行符的处理
  7. 到底什么是“机器学习”?机器学习有哪些基本概念?(简单易懂)
  8. JVM&NIO&HashMap简单问
  9. Android 完全退出程序,以及再按一次返回键退出程序
  10. Smartfox Server 2x 在 CentOS6.3 上的搭建
  11. python3参考手册_Python3 中文手册
  12. STEP 7-Micro/WIN SMART 界面介绍
  13. 演讲者模式投影到幕布也看到备注_PPT的备注功能怎么使用?如何让备注仅被演示者看到?...
  14. Axis2+Rampart(WSS4J)实现UsernameToken认证方式的WS-Security(基于SOAP的Web安全调用机制)
  15. win10分辨率不能调整_win10常规问题解决方案
  16. erp软件的优点和用途
  17. 如何将彩色文本打印到终端?
  18. 视觉和imu(惯性传感器)( 一)
  19. 测试用例------用户登录(很详细哦)
  20. VS生成桌面应用程序

热门文章

  1. 删除替换字符串中第一次出现的字符串
  2. Spring boot 通过ApplicationRunner在启动完成后按指定顺序执行任务
  3. ActiveMQ 在java中的使用,通过单例模式、工厂实现
  4. python-3.8.0安装
  5. AI 是中性的技术,如何用它更好地为人类服务
  6. 数据结构 之 并查集(Disjoint Set)
  7. Git协作流程(转)
  8. 图解ThreadLocal核心原理
  9. Spring源码 (事务篇) - 整体流程
  10. 计算机系统-实模式/保护模式/虚拟86模式