Wednesday, April 15, 2009

Chaining Properties file

In Java, one way of instantiating a Properties object is with Properties(Properties defaults) constructor. The "defaults" parameter allows property files to be stacked together and it is searched only when a particular property is not found. This feature is quite useful during development and testing when we often have conflicting settings. In such cases, editing a single properties file proves to be error-prone and inefficient. Having more than 1 properties file with only properties that need to be different and chaining them together proves to be more safe and easy. Here is an example:

import java.util.Properties;

public class LayeringProperties {

public static final String appPropFile = "Props";
public static final String userPropFile = "UserProperties";

public static void main(String[] args) throws IOException{

try {
//Load application's properties from a file
Properties myProps = new Properties();
myProps.load(new FileInputStream(appPropFile));

//Load the user's properties from a file
Properties userProps = new Properties(myProps);
userProps.load(new FileInputStream(userPropFile));

//List the user properties as key=value pairs
System.out.println("User properties");

//List the application's properties
System.out.println("Application properties");

} catch (FileNotFoundException fe) {
} catch (IOException ie) {

Here is the output. Notice how the property value for property "" is different in the 2 Properties object.
User properties
-- listing properties -- email Properties
Application properties
-- listing properties -- Properties

No comments:

Post a Comment