2014-11-25 43 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。我不得不调试它来发现这一点。