问题是当我尝试验证记录的字段时,
@NotNull
和 @NotBlank
不起作用。当我在没有参数之一的情况下调用我的服务时(它们不存在于 URL 中),我预计会收到 400 个错误的请求响应,但我会收到 500 个系统错误 (NPE),因为它在代码中走得更远,我不希望出现空值.
服务调用的URL: http://localhost:8080/api/client?searchKey=NAME&value=John
应该以 400 响应的无效 URL,但实际上它们没有: http://localhost:8080/api/client?searchKey=NAME 和 http://localhost:8080/api/client?value=John
聚合查询参数的记录:
@ValidPersonSearchParameter
public record PersonSearchParameters(
@NotNull SearchKey searchKey, // enum
@NotBlank String value
) {
}
@ValidPersonSearchParameter:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PersonSearchParameterValidator.class)
public @interface ValidPersonSearchParameter {
String message() default "Invalid search parameter";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
验证者:
public class PersonSearchParameterValidator implements ConstraintValidator<ValidPersonSearchParameter, PersonSearchParameters> {
private ConstraintValidatorContext context;
private PersonSearchParameters parameters;
@Override
public boolean isValid(PersonSearchParameters parameters, ConstraintValidatorContext context) {
// validation logic
// here I trust PersonSearchParameters to do validation, but it doesn't, so I get NPE
}
}
控制器:
@RestController
@RequestMapping(value = "/api/client", produces = APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
@Validated
public class PersonController {
@GetMapping
public PersonInfoResponse getPersonInfo(@Valid @NotNull PersonSearchParameters parameters) {
// business logic
}
}