如何配置DataBinder使用指定Locale识别逗号作为十进制分隔符
配置DataBinder识别逗号十进制分隔符的方法
根本原因
你设置全局Locale不生效的核心原因是:Spring DataBinder默认的字符串转数字类型转换器没有使用你配置的全局Locale,默认使用与系统Locale绑定的数字格式规则,无法识别法语区域的逗号分隔符。
修复方案
方案1:为当前DataBinder注册自定义属性编辑器(推荐,针对性强)
直接给当前DataBinder的double类型注册适配法语Locale的CustomNumberEditor即可,修改后的测试用例代码如下:
import org.springframework.beans.propertyeditors.CustomNumberEditor; import java.text.NumberFormat; import java.util.Locale; class DataBinderTest { class Foo { public double price; public void setPrice(double price) { this.price=price; } } @Test void testMapping() throws BindException { final var properties = new Properties(); properties.setProperty("price","0,00"); final var binder = new DataBinder(new Foo()); binder.setIgnoreUnknownFields(false); // 新增:注册适配法语Locale的double类型转换器 NumberFormat frenchNumberFormat = NumberFormat.getInstance(Locale.FRANCE); binder.registerCustomEditor(double.class, new CustomNumberEditor(double.class, frenchNumberFormat, true)); binder.bind(new MutablePropertyValues(properties)); if (binder.getBindingResult().hasErrors()) { throw new BindException(binder.getBindingResult()); } } }
其中CustomNumberEditor的第三个参数设为true表示允许空值,你可以根据业务需求调整。
方案2:全局配置ConversionService复用
如果有多个DataBinder都需要使用相同的Locale规则,可以预先配置通用的ConversionService,统一注入到所有DataBinder中:
import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.number.NumberFormatter; // 初始化全局转换服务 DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(); // 注册法语格式的数字转换器 conversionService.addFormatterForFieldType(double.class, new NumberFormatter("#,##0.00", Locale.FRANCE)); // 使用时给DataBinder设置转换服务即可 binder.setConversionService(conversionService);
两种方案都可以实现将0,00正确转换为0.0的double类型值,不会再抛出数字格式异常。
内容的提问来源于stack exchange,提问作者Datz
相关产品推荐
相关产品推荐

