views:

74

answers:

3

What is a best practice for storing user messages in a configuration file and then retrieving them for certain events throughout an application?

I was thinking of having 1 single configuration file with entries such as

REQUIRED_FIELD = {0} is a required field
INVALID_FORMAT = The format for {0} is {1}

etc. and then calling them from a class that would be something like this

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);
    }
}

Is this the right way to approach this problem or is there some de-facto standard already in place?

+2  A: 

Your approach is almost correct. I want to add one more thing. If you are talking about configuration file, it is always better to have two .properties file.

One for default configuration of the application. (let's say defaultProperties.properties)

Second for user-specific configuration (let's say 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();
. . .
Yatendra Goel
A: 

Spring already has support for doing this kind of thing. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#context-functionality-messagesource would be a good starting point

Calm Storm
+4  A: 

You're on the right track with putting the messages into a property file. Java makes this pretty easy if you use ResourceBundle. You basically create a property file containing your message strings for each locale you want to support (messages_en.properties, messages_ja.properties) and bundle those property files into your jar. Then, in your code, you extract the message:

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

When you load the bundle, Java will determine what locale you're running in and load the correct message. Then, you pass in your args along with the message string and create the localized message.

Reference for ResourceBundle.

Erich Douglass