【发布时间】:2016-10-21 07:47:36
【问题描述】:
如果我像这样注释命令对象字段,带有逗号和点的小数将被验证并正确绑定(我想要):
@NumberFormat(style=Style.NUMBER)
private Double amount;
但是,使用 @NumberFormat 以相同方式注释集合不起作用,因此我试图在全局 InitBinder 中重现此行为:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new NumberStyleFormatter());
}
但它仍然只接受逗号。
Spring 的注解处理器代码似乎也是如此,但它们同时接受逗号和点。我错过了什么?
public class NumberFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory<NumberFormat> {
@Override
public Set<Class<?>> getFieldTypes() {
return NumberUtils.STANDARD_NUMBER_TYPES;
}
@Override
public Printer<Number> getPrinter(NumberFormat annotation, Class<?> fieldType) {
return configureFormatterFrom(annotation);
}
@Override
public Parser<Number> getParser(NumberFormat annotation, Class<?> fieldType) {
return configureFormatterFrom(annotation);
}
private Formatter<Number> configureFormatterFrom(NumberFormat annotation) {
if (StringUtils.hasLength(annotation.pattern())) {
return new NumberStyleFormatter(resolveEmbeddedValue(annotation.pattern()));
}
else {
Style style = annotation.style();
if (style == Style.CURRENCY) {
return new CurrencyStyleFormatter();
}
else if (style == Style.PERCENT) {
return new PercentStyleFormatter();
}
else {
return new NumberStyleFormatter(); // THIS CASE
}
}
}
}
【问题讨论】:
标签: java spring spring-mvc