3.1三、@InitBinder 和 WebDataBinder

  這一部分示例見這個項目的 mvc 分支下的 WebDataBinderController.javahtml


① 用@InitBinder自定義數據綁定

  用@InitBinder註解的控制器方法,容許你直接在你的控制器類中配置 Web 數據綁定。@InitBinder標記初始化WebDataBinder的方法,WebDataBinder被用於填充被註解的處理方法的命令和表單對象參數。java

  這些初始化綁定器(Init-binder)方法支持@RequestMapping方法支持的全部參數,處理命令/表單對象以及相關的校驗結果對象。初始化綁定器方法必須不帶返回值,因此它們一般被聲明爲 void 的。典型的參數包括WebDataBinderWebRequest或者java.util.Locale,容許用代碼方式註冊特定上下文的編輯器(context-specific editors)。git

  下面的例子演示了使用@InitBinder爲全部的java.util.Date表單屬性配置一個CustomDateEditorweb

@Controller
public class MyFormController 
{
    @InitBinder
    protected void initBinder(WebDataBinder binder) 
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    // ...
}

  相對地,從 Spring 4.2 開始,考慮使用addCustomFormatter來指定Formatter實現以代替PropertyEditor實例。若是你剛好在一個共享的FormattingConversionService中也有一個個基於Formatter的設置(setup),這會很是用,一樣的規則能夠用重用於控制器指定的綁定規則的變化:spring

@Controller
public class MyFormController 
{
    @InitBinder
    protected void initBinder(WebDataBinder binder) 
    {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }
    // ...
}

② 配置一個自定義的WebBindingInitializer

  爲了表達(externalize)數據綁定初始化,你能夠提供一個自定義的WebBindingInitializer接口實現,而後你能夠經過爲RequestMappingHandlerAdapter來提供一個自定義 Bean 配置來啓動WebBindingInitializer,因此要重寫默認配置。mvc

  下面的例子來自 PetClinic 應用程序(雖然文檔上說了一下,可我也不知道這個項目在哪裏……),展現了一個配置,使用一個自定義WebBindingInitializer接口實現——org.springframework.samples.petclinic.web.ClinicBindingInitializer,它配置的PropertyEditors須要幾個控制器。app

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="cacheSeconds" value="0"/>
    <property name="webBindingInitializer">
        <bean class="org.springframework.samples.petclinic.web.ClinicBindingInitializer"/>
    </property>
</bean>

  @InitBinder方法也能夠定義在一個帶有@ControllerAdvice註解的類中,在這種狀況下,它們用於匹配控制器。這提供了一個使用WebBindingInitializer的代替方法。詳情見「使用@ControllerAdvice@RestControllerAdvice通知控制器一節」。編輯器

相關文章
相關標籤/搜索