Reading Property File in Java using Apache Commons Configuration

This tutorial demonstrates reading property file in Java using Apache Commons Configuration library.

You may have different configuration sources such as property files, XML files, system properties, environment variables etc. Apache Commons Configuration allows you to collect properties from many such sources and access them as a single configuration object. It also allows you to set the order of preference among the property sources to define an override mechanism.

Apache Commons Configuration provides a CompositeConfiguration class which represents a unified property bag to which you can attach different configuration sources. The properties of configuration sources that are added first hide the property values of configuration sources added later.

In the example below, we define two property sources namely Java system properties and a property file. A sample property file with a couple of sample properties is shown below. The idea is to specify the configuration properties in a property file and be able to override one or more of those properties from command line through java system properties.

Sample Property File

Java Code

Running the Java code

Output

Running the Java code with overridden values

We will now override properties – server.port and log.level, by specifying them as system properties with new values.

Output

Notice how the overridden values mask the values from the property file.

 


 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Previous article

Serialize Java object to JSON and back