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

Mas*_*ode 8 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);

}
Run Code Online (Sandbox Code Playgroud)

但问题是当我通过这样做将其限制为一个对象时,因为@InitBinder("customerEntity")它没有验证对象.所以我搜索了stackoverflow,发现@InitBinding它只适用于带注释的对象@ModelAttribute.然后我的问题是,@RequestBody当我使用它时工作正常,@InitBinder但是当我使用它时效果不好@InitBinder("customerEntity")......为什么会这样呢?是否有任何其他方法来验证与之关联的对象(不是单独的对象的属性)@RequestBody

whi*_*mot 5

这是一个老问题,但我已经设法获得@InitBinder注释以将我的自定义绑定Validator到这样的@Valid @RequestBody参数:

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

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


Ank*_*hal 3

从文档中,

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

请看这里