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.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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");
userProps.list(System.out);

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

} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}


Here is the output. Notice how the property value for property "admin.name" is different in the 2 Properties object.
User properties
-- listing properties --
admin.contact=phone email
application.name=My Properties
application.version=1.0
admin.name=akku
Application properties
-- listing properties --
application.name=My Properties
application.version=1.0
admin.name=Kutty

No comments:

Post a Comment