我有一些控制器有多个方法,每个都有不同的@RequestBody
域对象,有自己的验证器
@RestController
public class MyController {
@Autowired
private Validator BeanOneValidator;
@Autowired
private Validator BeanTwoValidator;
@Autowired
private Validator BeanThreeValidator;
@InitBinder("BeanOne")
private void initBeanOneBinder(WebDataBinder binder) {
binder.setValidator(beanOneValidator));
}
@InitBinder("BeanTwo")
private void initBeanTwoBinder(WebDataBinder binder) {
binder.setValidator(beanTwoValidator));
}
@InitBinder("BeanThree")
private void initBeanThreeBinder(WebDataBinder binder) {
binder.setValidator(beanThreeValidator));
}
@RequestMapping(...)
public requestWithBeanOne(@RequestBody @Valid BeanOne){...}
@RequestMapping(...)
public requestWithBeanTwo(@RequestBody @Valid BeanTwo){...}
@RequestMapping(...)
public requestWithBeanThree(@RequestBody @Valid BeanThree){...}
}
有没有一种方法可以为控制器注册多个绑定器,就像它们在这里一样,而无需声明多个 @InitBinder 注释方法?
做这样的事情是行不通的:
@InitBinder({"BeanOne","BeanTwo","BeanThree"})
private void initBeanOneBinder(WebDataBinder binder) {
binder.addValidators(beanOneValidator, beanTwoValidator, beanThreeValidator));
}
如果有一种方法可以全局注册验证器,而不必向@InitBinder
控制器添加显式方法也足够了。