0

我有一些控制器有多个方法,每个都有不同的@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控制器添加显式方法也足够了。

4

1 回答 1

1

你可以添加一个ControllerAdvice全局注册验证器的应用程序:

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();
    }
}
于 2015-11-10T08:24:09.920 回答