Commons Configuration2-quick Start Guide

Source: Internet
Author: User
Tags access properties expression engine

Original: 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, defines some properties related to accessing a database. We assume that it's stored as database.properties in the local file system:

Database.host = Db.acme.comdatabase.port = 8199database.user = Admindatabase.password =??? Database.timeout = 60000

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

New configurations (); Try {    = 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 is used to query the values for the stored Configurati On properties. For the purpose, numerous get methods for different property types is 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"= config.getstring ("database.user"= Config.getstring ("Database.password", "secret");  // provide a default long dbtimeout = Config.getlong ("Database.timeout");

Note 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 was to return null. (Methods that return a primitive type throw a exception because in the this case there is no null value.) It is possible to provide a default value which are 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 is stored in a natural-by just repeating tags. The example file for this section defines some directory paths, that is, is processed by an application. It is named Paths.xml and looks as follows:

<?XML version= "1.0" encoding= "Iso-8859-1"?><Configuration>  <processingStage= "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 the-the-this-this-is-thread-safe, and an-instance can be shared a nd reused to read multiple configuration sources), but this time we use the XML () method rather than Properti ES ():

 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 is class implements the Configuration interface, but offers some more functionality to access properties in a M ore structured manner. The reader may also has noticed, we passed a string to XML () and we used a java.io.File object in The properties Example. All these methods come in several overloaded variants allowing the caller-Specify the configuration source in different Ways:as a file, as a URL, or as a string. In the latter case, the file was searched for with various places, including at an absolute file path, at a relative file pat H, 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 F or regular configurations. There is some additional facilities that take the hierarchical nature of these sources to account. The properties in the example configuration can is read in the following:

String stage = config.getstring ("processing[@stage]"); List<String> paths = Config.getlist (String.  Class, "Processing.paths.path");

The keys for properties is generated by concatening the possibly nested tag names in the XML document (ignoring the root Element). For attributes, there are 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 is queried at once.

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

String Secondpath = config.getstring ("Processing.paths.path (1)");

For elements which is not repeated such indices can be dropped. It is also possible to set a alternative expression engine -the component that evaluates and interprets Configu Ration keys. There is a 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 is available for all properties. The following code fragment shows how the example properties of the 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 the 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 is passed an arbitrary value object. This can also is 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 is saved again to make the changes persistent. Otherwise, the changes is only in memory. IF configurations is-to-be changed, it's preferrable to obtain them via a different mechanism:aConfiguration Builder. Builders is the most powerful and flexible the construct configurations. They support many settings that impact the This is the configuration data is loaded and the resulting configuration object Beh Aves. Builders for file-based configurations also offer aSave ()Method, writes all configuration data, back to disk. Configuration builders is typically created using a fluent API which allows a convenient and flexible configuration of th E Builder. This API was described in the section Configuration builders. For simple use cases, theconfigurationsClass 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 =Newconfigurations ();Try{    //Obtain the configurationfilebasedconfigurationbuilder<xmlconfiguration> builder = Configs.xmlbuilder ("Paths.xml"); Xmlconfiguration Config=builder.getconfiguration (); //Update PropertyConfig.addproperty ("NewProperty", "NewValue"); //Save Configurationbuilder.save ();}Catch(ConfigurationException CeX) {//Something went wrong}

Commons Configuration2-quick Start Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.