简体   繁体   中英

Does javax validation work with inheritance?

I am trying to validate a model, which is inheriting from another model and this parent model has @NotBlank annotation to validate a parameter. But this validation is bypassed in the controller which is accepting a list of child class objects.

The code snippet should give a fair idea of the scenario

public abstract class A {
  @NotBlank
  private String name;
}

public class B extends A {
  private String type;
}

@PostMapping(consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveRoles(@Valid @RequestBody List<B> roles){
   // ideally it should not land here if request has blank name. But it seems to land here.
   // logic 
}

The request body -

[
    {
        "name": "",
        "type": "system"
    }
]

You trying to validate the collection itself, but not the collection elements. Try this:

@PostMapping(consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveRoles(@RequestBody List<@Valid B> roles){
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM