我已经搜索和尝试了 2 天。我最终选择定义一个自定义的 PropertyEditorRegistar。这样,我可以仅修复双字段格式的区域设置。但是,我认为这不是最好的解决方案,因为它将应用于我的所有 Double 字段。但与此同时,它的工作做得很好。因此,如果有人有更好的解决方案,我会很乐意对其进行测试并更新我的代码。
所以我就是这样设置的:
1 - 创建一个新的实现 PropertyEditorRegistrar 的 groovy 类(如果您已经有,只需在现有的方法中添加该方法包含的部分代码)
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
public class CustomDoubleRegistrar implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
//define new Double format with hardcoded Locale.ENGLISH
registry.registerCustomEditor(Double.class,
new CustomNumberEditor(Double.class,
DecimalFormat.getInstance(Locale.ENGLISH),true))
}
}
2- 将自定义注册器定义到 conf/spring/resources.goovy 中(当然如果它还没有的话)
beans = {
customPropertyEditorRegistrar(CustomDoubleRegistrar)
}
3- 就是这样,Grails 自动数据绑定可以正常工作
Test t = new Test(params);
//params contains many Double fields with dot '.' as decimal delimiter
不要犹豫,发布更好的解决方案...
谢谢
编辑 1
自 Grails 2.3 以来,此解决方案不再有效。如果你仍然想使用这个方案,你必须把这个配置添加到 Config.groovy 文件中
grails.databinding.useSpringBinder = true
或者实现一个新的DataBinding。我已经尝试了其中的一些,但似乎没有任何东西可以解决小数分隔符问题。感谢您发布答案,如果您知道如何...
编辑 2
从 Grails 2.4+ 开始,您可以定义自己的 ValueConverter 来绕过基本的 Locale 验证。请注意,您必须删除在初始帖子和编辑 1 中所做的更改。以下是自定义 ValueConverter 的实现方法:
conf/spring/resources.groovy
// Place your Spring DSL code here
beans = {
"defaultGrailsjava.lang.DoubleConverter"(DoubleValueConverter)
}
class DoubleValueConverter implements ValueConverter {
public LongValueConverter() {
}
boolean canConvert(value) {
value instanceof Double
}
def convert(value) {
//In my case returning the same value did the trick but you can define
//custom code that takes care about comma and point delimiter...
return value
}
Class<?> getTargetType() {
return Double.class
}
}