Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring从属性文件获取枚举值_Java_Spring_Jsp_Enums_Messages - Fatal编程技术网

Java Spring从属性文件获取枚举值

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

我有一个枚举,其中值以utf8格式显示。因此,我的jsp视图中存在一些编码问题。是否有方法从我的
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)