Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Different Locale for @NumberFormat in Spring

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.

like image 693
Bahattin Ungormus Avatar asked Nov 02 '22 07:11

Bahattin Ungormus


1 Answers

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.

like image 161
Rafael Winterhalter Avatar answered Nov 15 '22 05:11

Rafael Winterhalter