2013-05-21 58 views
0

我試圖使用一種形式的ENUM:選擇這樣:注入的MessageSource到一個枚舉

<form:select path="myEnum"> 
    <form:options itemLabel="resourceBundleLabel" /> 
</form:select> 

,看起來像一個枚舉:

public enum MyEnum { 
    ONE("rb.one"), TWO("rb.two"); 

    private MessageSource messageSource; 

    private String rbKey; 

    public String getResourceBundleLabel() { 
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
    Locale locale = request.getLocale(); 
    return messageSource.getMessage(this.rbKey, null, locale); 
    } 

    public MyEnum(String rbKey) { 
    this.rbKey = rbKey; 
    } 
} 

的問題是,我似乎無法弄清楚如何獲取MessageSource注入。我嘗試添加@Component和@Autowired(因爲沒有默認構造函數而出現錯誤,然後嘗試將@Component切換到@Configurable,然後嘗試刪除註釋和實現MessageSourceAware,在所有情況下,messageSource爲null進入getResourceBundleLable()。

最終,我試圖完成的是使用Enum構建選擇選項,但是使它成爲使用適當的資源包和本地的選項。我只是在浪費我的時間的東西,是不是可行呢?

+1

我建議您至多隻在您的枚舉中存儲消息代碼。您目前的設計將您的枚舉與servlet環境非常緊密地結合在一起 - 如果您希望將來在其他地方使用此枚舉,該怎麼辦? –

+0

我想這種方法,但是Spring form:options不允許我使用資源包來設置標籤。我能看到的唯一方法就是解析Enum中的消息密鑰。 – CodeChimp

回答

2

見我的回答here如何用最少的管道依賴注入枚舉。

0

你ç一個也見here我的答案。它不會注入它,而是將其用作靜態方法。