java 如何从 Enum 中的 Spring Messagesource 读取内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2183252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read contents from Spring Messagesource within a Enum?
提问by simon
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).
我有一个包含三种不同状态类型的枚举。这些状态应该显示在发送给用户的电子邮件中,包含要显示的状态的字符串存储在 messages.properties 中(使用 Spring 类 org.springframework.context.MessageSource 的实现读取)。这在普通的 Spring 控制器中运行良好。但是,我更愿意在 Enum 中获得“显示状态”(将逻辑包含在一个地方)。
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.
但是,像下面的代码一样将消息源自动连接到枚举似乎不起作用,因为 messageSource 属性始终为空。
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)?
如何在 Enum 中使用自动连接的消息源(或者是否有其他方法可以实现我正在尝试的功能)?
回答by simon
I found the solution from this answer on SO: Using Spring IoC to set up enum values
我从 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:
这给了我使用 java.util.ResourceBundle 读取消息的指针,如下所示:
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;
}
}

