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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With