Alex Rivera | Logout

Use properties file instead of static final variables

Asked 2012-01-18T13:12:25.797
11

I have many classes with static final fields which are used as default values or config. What is best approach to create global config file? Should I move these fields to single static class, use properties file or what?

Edit: I need to use this values both in java classes and xhtml pages. Values dosen't depend on envirnoment. I could compile project to set new values - no problem.

Edit
Report

1 Answer

1

My favorite approach is the follow:

public class MyProperties {
private static final String BUNDLE_NAME = "my.package.MyProperties"; //$NON-NLS-1$

private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
        .getBundle(BUNDLE_NAME);


private MyProperties() {
}

public static long getLong(String key) {
    String strValue = getString(key);
    long result = -1;
    try {
        result = Long.parseLong(strValue);
    } catch (Exception exc) {
        logger.error(exc.getLocalizedMessage());
    }
    return result;
}

public static int getInteger(String key) {
    String strValue = getString(key);
    int result = -1;
    try {
        result = Integer.parseInt(strValue);
    } catch (Exception exc) {
        logger.error(exc.getLocalizedMessage());
    }
    return result;
}

public static String getString(String key) {
    String returnValue = System.getProperty(key);
    if(returnValue != null && returnValue.length() > 0) {
        if(logger.isDebugEnabled()) {
            logger.debug(key+" assigned by system property");
        }
        return returnValue;
    }
    try {
        returnValue = RESOURCE_BUNDLE.getString(key);
    } catch (MissingResourceException e) {
        returnValue = '!' + key + '!';
    }
    return returnValue;
}
}

This simple class first search the key in the system properties then in the resource bundle. This means you can override the property settings with -Dkey=value command line options.

answered 2012-01-18T13:50:16.020

Your Answer