How can I read contents from Spring Messagesource within a Enum?
I found the solution from this answer on SO: Using Spring IoC to set up enum values
This gave me the pointer to use java.util.ResourceBundle to read the messages, like this:
public enum InitechStatus{
OPEN("open"), CLOSED("closed"), BROKEN("broken");
private static ResourceBundle resourceBundle = ResourceBundle.getBundle("messages",
Locale.ENGLISH);
public final String name;
@Autowired
private MessageSource messageSource;
InitechStatus(String name) {
this.name = name;
}
@Override
public String toString() {
String displayStatusString = resourceBundle.getString("page.systemadministration.broadcastmail.status."
+ this.name);
return displayStatusString;
}
}
simon
Updated on June 05, 2022Comments
-
simon almost 2 years
I have an Enum containing three different Status types. These statuses should be displayed in an email sent to users, and the strings containing the statuses to be displayed are stored in messages.properties (read using an implementation of Spring class org.springframework.context.MessageSource). This works well in a normal Spring controller. However, I would prefer to get the "display status" within the Enum (to contain the logic in one place).
However, auto-wiring the messagesource to the enum as in the following code does not seem to work, as the messageSource property is always empty.
public enum InitechStatus{ OPEN("open"), CLOSED("closed"), BROKEN("broken"); public final String name; @Autowired private MessageSource messageSource; InitechStatus(String name) { this.name = name; } @Override public String toString() { String displayStatusString = messageSource.getMessage("page.systemadministration.broadcastmail.status." + this.name, null, Locale.ENGLISH); return displayStatusString; } }
How can I use the auto-wired messagesource within the Enum (or is there some other way to achieve what I'm trying)?
-
laura about 12 yearsHey, thanks for the answer - it looks so close to what I need... however, some of my messages need params - i.e. org.hibernate.validator.constraints.Length.message = length must be between {min} and {max} . I don't suppose you know a way around this?
-
simon about 12 yearsTo achieve this you could probably use java.text.MessageFormat (docs.oracle.com/javase/6/docs/api/java/text/MessageFormat.html). Also see docs.oracle.com/javase/tutorial/i18n/format/messageFormat.html