Adding multiple validators using initBinder

后端 未结 8 1526
傲寒
傲寒 2020-12-04 18:04

I\'m adding a user validator using the initBinder method:

@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setVa         


        
8条回答
  •  没有蜡笔的小新
    2020-12-04 18:44

    I do not see a reason why Spring does not filter out all validators which are not applicable to the current entity by default which forces to use things like CompoundValidator described by @Rigg802.

    InitBinder allows you to specify name only which give you some control but not full control over how and when to apply your custom validator. Which from my perspective is not enough.

    Another thing you can do is to perform check yourself and add validator to binder only if it is actually necessary, since binder itself has binding context information.

    For example if you want to add a new validator which will work with your User object in addition to built-in validators you can write something like this:

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
      Optional.ofNullable(binder.getTarget())
          .filter((notNullBinder) -> User.class.equals(notNullBinder.getClass()))
          .ifPresent(o -> binder.addValidators(new UserValidator()));
    

    }

提交回复
热议问题