【发布时间】:2022-01-22 18:31:33
【问题描述】:
所以我在Spring Boot 中有一个Rest Controller,对于端点,我需要验证它的Request Body。
控制器:
@RestController
@Validated
@RequestMapping("/my_endpoint")
public class WorkflowController {
@PostMapping(value = "/blablabla/", consumes = MediaType.APPLICATION_JSON_VALUE)
public List<Object> createDisconnectRequestRest(@RequestBody List<@CustomValidator @Valid RequestObj> dtos) { // here at the validators is the question
... //nevermind
return null;
}
请求对象:
@Data
public class RequestObj{
private String comment;
@NotNull // this @NotNull annotation validator is triggered AFTER the custom validator is done. I want this to be first validated and then the custom validator should take place
private List<Long> ids = new ArrayList<>();
}
@Target({FIELD, TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
@Documented
public @interface ValidRequest {
String message() default "Invalid request";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义验证器:
public class CustomValidator implements ConstraintValidator<ValidRequest, RequestObj> {
// repositories, constructor
@Override
public boolean isValid(RequestObj request, ConstraintValidatorContext constraintValidatorContext) {
myRepository.findAllById(request.getIds()); // I want the @NotNull annotation validate the object before this custom validator
return true;
}
}
这是问题:
要触发的第一个是 CustomValidator,然后正在验证 RequestObj。换句话说,验证从@CustomValidator 注释开始,然后是@Valid 注释。我希望第一个被触发的是@Valid 注释(所以@NotNull 注释将首先验证对象)然后@CustomValidator 应该完成它的工作。例如,如果 body 字段 ids 为 NULL,我希望 @CustomValidator 甚至无法启动,因为验证已经失败。
【问题讨论】:
-
您是否尝试过更改注释的顺序?
-
是的,没用。
标签: java spring-boot validation spring-restcontroller spring-validator