Spring MVC - @Valid on list of beans in REST service

后端 未结 10 2190
醉酒成梦
醉酒成梦 2020-11-29 23:05

In a Spring MVC REST service (json), I have a controller method like this one :

@RequestMapping(method = RequestMethod.POST, value = { \"/doesntmatter\" })
         


        
10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 23:33

    Using com.google.common.collect.ForwardingList

    public class ValidList extends ForwardingList {
    
      private List<@Valid T> list;
    
      public ValidList() {
        this(new ArrayList<>());
      }
    
      public ValidList(List<@Valid T> list) {
        this.list = list;
      }
    
      @Override
      protected List delegate() {
        return list;
      }
    
      /** Exposed for the {@link javax.validation.Validator} to access the list path */
      public List getList() {
        return list;
      }
    }
    

    So no need for the wrapper

    you may use

    @RequestMapping(method = RequestMethod.POST, value = { "/doesntmatter" })
    @ResponseBody
    public List<...> myMethod(@Valid @RequestBody ValidList request, BindingResult bindingResult) {
    

    By using wrapper your JSON needs to be changed to

    {
      "list": []
    }
    

    with this implementation you can use original JSON

    []
    

提交回复
热议问题