Spring从属性文件中获取枚举值
问题描述:
我有一个枚举值以utf8格式显示。正因为如此,我在jsp视图中遇到了一些编码问题。有没有办法从我的messages.properties
文件中获取值。如果我在属性文件中有以下几行:Spring从属性文件中获取枚举值
shop.first=Первый
shop.second=Второй
shop.third=Третий
如何将它们注入枚举?
public enum ShopType {
FIRST("Первый"), SECOND("Второй"), THIRD("Третий");
private String label;
ShopType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
答
我经常有类似的用例,我通过把键(不是本地化的值)作为枚举属性来处理。使用ResourceBundle
(或使用Spring时的MessageSource
),我可以在需要时解析任何这样的本地化字符串。这种方法有两个优点:
- 所有本地化字符串可以存储到一个单一的文件
.properties
,这消除了Java类的所有编码的担忧; - 它使代码完全可本地化(实际上,它将是每个语言环境的一个
.properties
文件)。
这样,你的枚举会是这样的:
public enum ShopType {
FIRST("shop.first"), SECOND("shop.second"), THIRD("shop.third");
private final String key;
private ShopType(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
(我删除了二传手,因为一个枚举属性应始终只读不管怎么说,这是没有必要的了。)
您的.properties
文件保持不变。
现在到了时间来获得本地化的店铺名称...
ResourceBundle rb = ResourceBundle.getBundle("shops");
String first = rb.getString(ShopType.FIRST.getKey()); // Первый
希望这将有助于...
杰夫
+1
请小心使用此方法。 'java.util.ResourceBundle#getBundle(java.lang.String)'不支持'UTF-8'编码,假定使用'ISO 8859-1'字符编码。如果你的本地化文件包含这样的字符,你需要使用'java.util.Properties#load(java.io.Reader)' – GokcenG 2017-10-14 13:10:25
的可能的复制http://stackoverflow.com/问题/ 17167144/make-enum-tostring-localized – dkateros 2014-10-08 06:13:53