2012-02-07 86 views
5

我在Spring的DataBinder和ConversionService中将Web请求绑定到模型对象的用法和用途方面存在一些混淆。这是因为我最近试图通过添加来使用JSR-303验证。Spring中的DataBinder和ConversionService之间的区别

在此之前,我用:

<bean 
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="webBindingInitializer"> 
     <bean class="mypackage.GlobalWebBindingInitializer" /> 
    </property> 
</bean> 

这是一件好事,因为我想,可能由几个控制器使用的全局DataBinder的。 内GlobalWebBindingInitialzer类实现这几条:

binder.registerCustomEditor(MyClass.class, new PropertyEditorSupport(MyClass.class) 

不过,我想用@Valid注释等加入。这样做的副作用是上面的AnnotationMethodHandlerAdapter bean已经被定义为注解驱动的一部分,所以我的全局数据绑定被忽略。

所以现在我已经创建了这个类:

public class MyClassConverter implements Converter<String, MyClass> 

我很困惑。如果我想使用,我应该使用转换服务而不是数据绑定?

回答

3

从历史上看,Spring的数据绑定被用于将数据转换为javabeans。它非常依赖JavaBean PropertyEditors来完成转换。

Spring 3.0 added new and different support用于转换和格式设置。其中一些更改包括一个“core.convert”包和一个“格式”包,根据文档“可以作为PropertyEditor的简单替代品”。

现在,回答你的问题,是的,它看起来像你在正确的轨道上。您可以继续使用,但是在很多情况下,您应该可以使用转换器而不是数据联编程序来简化长篇故事。

有关如何添加验证的文档is available online

1

此外回答上述属性编辑(尤指PropertyEditorSupport)不是线程安全这是在其中每个请求被在单独的线程所服务的Web环境特别需要。理论上,PropertyEditors在高度并发条件下会产生不可预知的结果。

但不知道为什么Spring中使用属性编辑器摆在首位。可能是SpringMVC之前的非多线程环境和日期?

编辑:

虽然PropertyEditorSupport看起来不是线程安全的春节,确保它在一个线程安全的方式使用。例如,每次需要数据绑定时都会调用initBinder()。我错误地认为它在控制器初始化时只调用过一次。

@InitBinder 
public void initBinder(WebDataBinder binder) { 

    logger.info("initBinder() called."); 

    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); 
    dateFormat.setLenient(false); 

    binder.registerCustomEditor(Date.class, new CustomDateEditor(
      dateFormat, false)); 
} 

这里的日志“initBinder()调用。”可以在绑定发生时多次显示。

相关问题