Use Different Locale for @NumberFormat in Spring

谁都会走 提交于 2019-12-19 08:15:12

问题


I am working on a Spring 3 project and I need to format a Long field for Turkish currency. The default Locale of the application is en_US. I used the @NumberFormat annotation as below:

@NumberFormat(style=NumberFormat.Style.CURRENCY)
public Long getBudgetLimit() {
    return budgetLimit; 
}

The annotation works and formats the form field in English locale. However I need to use Turkish locale for this field. Is there a way to set the locale of a single field or a page different than the application's locale?

Edit: I just found the answer myself. Use a custom editor in the controller as below:

NumberFormat numberFormat = NumberFormat.getNumberInstance(new Locale("tr","TR"));
dataBinder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class,numberFormat, true));

and do not use the @NumberFormat annotation. For same reason it gave an error for me.


回答1:


There are many ways but you could for example register a custom implementation of AnnotationFormatterFactory<NumberFormat> as a bean which would allow you to handle the formatting manually. This is documentented in the Spring documentation section 6.6. The example in the documentation even handles the use case of adjusting @NumberFormat's behavior.



来源:https://stackoverflow.com/questions/21091086/use-different-locale-for-numberformat-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!