我有一个api,它包含一个接受对象作为请求主体的方法。我想做的是应用条件验证。查看下面的代码:
@Override
@PostMapping(value = "/private/getUsers/",
produces = {"application/json"},
consumes = {"application/json"})
public ResponseEntity<Object> getUsers(@ApiParam(value = "Request object for users", required = true)
@Valid @RequestBody USerType userType) {
//do stuff here
return new ResponseEntity<>(Object, HttpStatus.OK);
}
class UserType {
TypeEnum typeEnum
String name;
String adminId
//getters and setters
}
因此,如果传递的UserType对象包含一个等于admin的TypeEnum,我想进行验证,以确保adminID通过,如果传入的TypeEnm是出纳类型,我不想强制执行此验证
您可以使用@AssertTrue
添加自定义验证。试试这个类:
class UserType {
TypeEnum typeEnum
String name;
String adminId
//getters and setters
@AssertTrue
public boolean isValid() {
if (TypeEnum.admin == typeEnum) {
if (check admin id not blank){
return true;
}
return false;
}
return true;
}
}