存储和检索错误消息的最佳实践

时间:2010-03-08 17:16:49

标签: java configuration user-interface

将用户消息存储在配置文件中然后在整个应用程序中检索某些事件的最佳做法是什么?

我在考虑使用一个包含

等条目的单个配置文件
REQUIRED_FIELD = {0} is a required field
INVALID_FORMAT = The format for {0} is {1}

等。然后从类似这样的类中调用它们

public class UIMessages {
    public static final String REQUIRED_FIELD = "REQUIRED_FIELD";
    public static final String INVALID_FORMAT = "INVALID_FORMAT";

    static {
        // load configuration file into a "Properties" object
    }
    public static String getMessage(String messageKey) {
        // 
        return properties.getProperty(messageKey);
    }
}

这是解决这个问题的正确方法,还是已经有一些事实上的标准?

3 个答案:

答案 0 :(得分:8)

您将消息放入属性文件中是正确的。如果使用ResourceBundle,Java会非常简单。您基本上创建了一个属性文件,其中包含您要支持的每个区域设置的消息字符串(messages_en.propertiesmessages_ja.properties),并将这些属性文件捆绑到您的jar中。然后,在您的代码中,您将提取消息:

ResourceBundle bundle = ResourceBundle.getBundle("messages");
String text = MessageFormat.format(bundle.getString("ERROR_MESSAGE"), args);

加载捆绑包时,Java将确定您正在运行的区域设置并加载正确的消息。然后,将args与消息字符串一起传入并创建本地化消息。

ResourceBundle的参考。

答案 1 :(得分:3)

你的方法几乎是正确的。我想补充一点。如果您在谈论配置文件,最好有两个.properties文件。

一个用于应用程序的默认配置。 (让我们说defaultProperties.properties

第二个用户特定配置(假设为appProperties.properties

. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();

// create application properties with default
Properties applicationProps = new Properties(defaultProps);

// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .

答案 2 :(得分:0)