Java Spring从属性文件获取枚举值
我有一个枚举,其中值以utf8格式显示。因此,我的jsp视图中存在一些编码问题。是否有方法从我的Java Spring从属性文件获取枚举值,java,spring,jsp,enums,messages,Java,Spring,Jsp,Enums,Messages,我有一个枚举,其中值以utf8格式显示。因此,我的jsp视图中存在一些编码问题。是否有方法从我的messages.properties文件中获取值。如果我的属性文件中有以下行怎么办: shop.first=Первый shop.second=Второй shop.third=Третий 如何将它们注入enum public enum ShopType { FIRST("Первый"), SECOND("Второй"), THIRD("Третий"); pr
messages.properties
文件中获取值。如果我的属性文件中有以下行怎么办:
shop.first=Первый
shop.second=Второй
shop.third=Третий
如何将它们注入enum
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;
}
}
(我删除了setter,因为枚举属性应该始终是只读的。无论如何,不再需要它了。)
您的.properties
文件保持不变
现在是时候获得本地化的店名了
ResourceBundle rb = ResourceBundle.getBundle("shops");
String first = rb.getString(ShopType.FIRST.getKey()); // Первый
希望这将有助于
Jeff可能的重复使用此方法时要小心
java.util.ResourceBundle#getBundle(java.lang.String)
不支持UTF-8
编码,假设使用ISO 8859-1
字符编码。如果本地化文件包含此类字符,则需要使用java.util.Properties\load(java.io.Reader)