Use properties file instead of static final variables

后端 未结 6 1507
轮回少年
轮回少年 2021-02-08 03:05

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

6条回答
  •  礼貌的吻别
    2021-02-08 03:45

    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.

提交回复
热议问题