2012-02-07 25 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()調用。」可以在綁定發生時多次顯示。