springvalidationspring-mvc-initbinders

Spring MVC Validator. encapsulate multiple validator initialization for multiple request mappings


I have a some controllers that have multiple methods, each with a different @RequestBody domain object having its own validator

@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){...}
}

Is there a way to register multiple binders for a controller like they are here without declaring multiple @InitBinder annotated methods?

Doing something like this doesn't work:

    @InitBinder({"BeanOne","BeanTwo","BeanThree"})
    private void initBeanOneBinder(WebDataBinder binder) {
        binder.addValidators(beanOneValidator, beanTwoValidator, beanThreeValidator));
    }

If there was a way to register the validators globally without having to add the explicit @InitBinder method to the controller that would suffice as well.


Solution

  • You can add a ControllerAdvice to your application that registers your validator globally:

    import org.springframework.validation.DataBinder;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.InitBinder;
    
    @ControllerAdvice
    public class ValidatorAdvice {
    
        @InitBinder
        public void initBinder(DataBinder dataBinder) {
           // dataBinder.addValidators();
        }
    }