Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring get enum values from properties file

I have an enum where values are presented in utf8 format. Because of this i have some encoding problems in my jsp view. Is there a way to get values from my messages.properties file. What if i have following lines in my properties file:

shop.first=Первый
shop.second=Второй
shop.third=Третий

How can i inject them in 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;
    }
}
like image 419
user3127896 Avatar asked Oct 08 '14 06:10

user3127896


1 Answers

I often have similar use cases, which I handle by putting the keys (not the localized values) as enum properties. Using a ResourceBundle (or a MessageSource when using Spring), I can resolve any such localized string whenever needed. This approach has two advantages:

  1. All localized strings can be stored into one single .properties file, which eliminates all encoding concerns in Java classes;
  2. It makes the code fully localizable (in fact, it will be one .properties file per locale).

This way, your enum will look like:

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;
    }
}

(I removed the setter since an enum property should always be read-only. Anyway, it's not necessary anymore.)

Your .properties file remains the same.

Now comes the time to get a localized shop name...

ResourceBundle rb = ResourceBundle.getBundle("shops");
String first = rb.getString(ShopType.FIRST.getKey()); // Первый

Hope this will help...

Jeff

like image 88
Jeff Morin Avatar answered Nov 17 '22 16:11

Jeff Morin