在Spring中为@NumberFormat使用不同的语言环境 [英] Use Different Locale for @NumberFormat in Spring

查看:473
本文介绍了在Spring中为@NumberFormat使用不同的语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事Spring 3项目,我需要格式化土耳其货币的Long字段.应用程序的默认Localeen_US.我使用了@NumberFormat注释,如下所示:

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

,请勿使用@NumberFormat批注.出于同样的原因,它给了我一个错误.

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

推荐答案

有很多方法,但是您可以例如将AnnotationFormatterFactory<NumberFormat>的自定义实现注册为bean,这将允许您手动处理格式.这是在Spring文档部分中记录的 6.6 .文档中的示例甚至处理了调整@NumberFormat行为的用例.

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.

这篇关于在Spring中为@NumberFormat使用不同的语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆