2014-11-25 44 views
4

如果我使用@InitBinder而沒有限制它,它使用@RequestBody正常工作來驗證我的對象。@InitBinder在春季開機不能使用@RequestBody

@InitBinder 
private void initBinder(WebDataBinder binder) { 
    binder.setValidator(validator); 
} 



@RequestMapping(method=RequestMethod.POST) 
public CustomerQuickRegisterEntity saveNewCustomer(@Valid @RequestBody CustomerQuickRegisterEntity customerEntity,BindingResult result) 
{ 
    if(result.hasErrors()) 
    { 
     return new CustomerQuickRegisterEntity(); 
    } 
    return customerQuickRegisterRepository.save(customerEntity); 

} 

但問題是,當我把它限制在做它作爲@InitBinder("customerEntity")它不是驗證對象只是一個對象。所以我已經通過stackoverflow進行搜索,發現@InitBinding只適用於註釋爲@ModelAttribute的對象。然後我的問題是,它與@RequestBody工作正常,當我使用它作爲@InitBinder,但當我使用它作爲@InitBinder("customerEntity") ......它爲什麼如此呢? 是否有任何其他的方法來驗證具有@RequestBody

+1

由於綁定框架('@ ModelAttribute')與用於'@ RequestBody'的消息轉換框架完全不同,它不能與'@ RequestBody'一起使用。使用'@ RequestBody'時不使用活頁夾。帶參數的方法總是被調用,帶有參數的方法只被調用名爲'customerEntity'的模型對象,它不會被調用。 – 2014-11-25 06:29:17

+0

但是,當我將它用作'@ InitBinding'而不將其限制爲任何特定對象時,它可以正常使用'@ RequestBody'。這是令人困惑的 – MasterCode 2014-11-25 06:32:08

+0

@DineshShende看看[這裏](http://stackoverflow.com/questions/17341543/initbinder-not-working-for-specific-model-attribute) – 2014-11-25 06:32:49

回答

3

從文檔相關聯的對象(對象的不屬性獨立),

默認值是適用於由處理的所有命令/形式屬性和所有請求 參數註釋的處理程序類。在此處指定模型 屬性名稱或請求參數名稱將這些初始綁定器方法限制爲這些特定屬性/參數,其中 不同的初始綁定器方法通常應用於屬性或參數的不同組 。

請看看here

0

這是一個老問題,但我設法讓@InitBinder註釋到我的自定義綁定Validator@Valid @RequestBody參數是這樣的:

@InitBinder 
private void bindMyCustomValidator(WebDataBinder binder) { 
    if ("entityList".equals(binder.getObjectName())) { 
     binder.addValidators(new MyCustomValidator()); 
    } 
} 

如果嘗試通過設置註釋的值來過濾綁定的參數,那麼它將不適用於@RequestBody參數。所以我在這裏檢查對象名稱。我的方法參數實際上被稱爲entities,但Spring已決定將其稱爲entityList。我不得不調試它來發現這一點。