春季启动时@InitBinder无法使用@RequestBody

时间:2014-11-25 06:24:34

标签: spring spring-mvc spring-boot

如果我使用@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

关联的对象(不是单独的对象的属性)

3 个答案:

答案 0 :(得分:3)

来自文档,

  

默认是应用于所有命令/表单属性和所有请求   由带注释的处理程序类处理的参数。指定模型   这里的属性名称或请求参数名称限制了   init-binder方法到那些特定的属性/参数,用   不同的init-binder方法通常适用于不同的组   属性或参数。

请查看here

答案 1 :(得分:3)

这是一个老问题,但我已设法获取@InitBinder注释,将我的自定义Validator绑定到@Valid @RequestBody参数,如下所示:

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

如果您尝试通过设置注释的值来过滤绑定参数,那么它将不适用于@RequestBody参数。所以我在这里检查对象名称。我的方法参数实际上称为entities,但Spring决定将其称为entityList。我不得不调试它来发现这个。

答案 2 :(得分:1)

您可以尝试我的解决方案:

@InitBinder
private void initBinder(WebDataBinder binder) {
    if (CustomerQuickRegisterEntity.class.equals(binder.getTarget().getClass())) {
        binder.addValidators(new YourValidator());
    }
}
相关问题