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 :
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


× six = 6



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books