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 norma开发者_如何学运维l 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)?
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;
}
}
精彩评论