Use java.util.prefs.Preferences instead of java.util.Properties

A typical installer for an application needs to ask the user a couple of options and some of these are configuration questions e.g. the port on which the application should run, how it should run etc. The application has to remember these options and use them in every run. Standard manner of solving such a problem is to write these options in a properties file which can be loaded at the start-up of the application. But then again the problem shifts to some other area i.e. remember the install path and then load the required properties file from the installed path.

Remembering installed path can be solved by setting an environment variable e.g. MYAPP_HOME. The variable can be initialized with the required value while installing so that every time the application gets loaded the variable will be set. This is a typical solution that is employed in most of the projects.

The Other Solution

The Preferences API that is provided JDK can be used to solve this typical problem. Preferences work just like properties but they are persistent unlike Properties. At the back, when a preference is written it gets stored to a backing store. When you ask for the preference, the value is then loaded from this store. On a typical Windows machine the default store is Windows registry but the store is configurable and you can change it to what ever you like e.g. a file.

Writing a preference is straight forward. Unlike properties which are String based key-value pairs the preferences have keys that are Strings but you can store values of all basic types e.g. long, boolean, double etc.

public class StaticPreferenceFactory {
    public static void main(String args[]) throws Exception {
        Preferences prefsRoot = Preferences.userRoot();
        Preferences myPrefs = prefsRoot
                .node("com.myapp.preference.staticPreferenceLoader");
        myPrefs.put("fruit", "apple");
        myPrefs.putDouble("price", 40);
        myPrefs.putBoolean("available", false);
        return prefsRoot;
    }
}

Just like we have system variables and user variables. There is a system preference node that you can get by calling systemRoot() and there is a user preference node that you get calling userRoot() node. Once a preference is stored in a userNode it is not accessible to other users of the system just like user variables. You can clear the preferences written by calling the clear() API.

public class UsePreference {
    public static void main(String args[]) throws Exception {
        Preferences myfilePrefs = Preferences.userRoot();
        myfilePrefs = myfilePrefs
                .node("com.myapp.preference.staticPreferenceLoader");
        System.out.println("finding fruit:"
                + myfilePrefs.get("fruit", "not found") + " available :"
                + myfilePrefs.getBoolean("available", true));
    }
}

Retrieving a preference is also straight forward just like properties. The get API here takes two arguments the key, to be found, and default value, incase the value is not found.

Spring also provides PreferencesPlaceholderConfigurer that can be used to load preferences.

<bean id="preferencePlaceHolder"
	class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
	<property name="userTreePath" value="com.myapp.preference.staticPreferenceLoader" />
</bean>
<bean id="myEntity" class="info.dependencyInjection.spring.factory.MyEntity">
	<property name="value" value="${fruit}" />
</bean>

For our installer problem we can store all our configuration options in Preferences while installing and the application will be only concerned about reading these values. This way we can avoid all the pains of writing to environment variables and making sure that we load the proper variables every time.

Reference: Use java.util.prefs.Preferences instead of java.util.Properties from our JCG partner Rahul Sharma at the “The road so far…” blog.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


+ four = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close