首页 > 解决方案 > 使用自定义验证器进行 Spring Bean 验证

问题描述

我已经实现了自定义大小验证,以便将“errorCode”添加到验证错误中。

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { StringLengthValidator.class })
public @interface StringLength {

    String message() default "Size must be between {min} and {max}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    long min() default 0L;

    long max();

    String errorCode() default "";

}

我在我的 DTO 中注释了以下字段:

@StringLength(min = 5, max = 400, errorCode = "1000001")

@RestControllerAdvice我添加了以下内容:

@ExceptionHandler({WebExchangeBindException.class})
Mono<ResponseEntity<...>> webExchangeBindException(WebExchangeBindException exception, ServerHttpRequest request) {
    ...
}

如何获取原始注释的错误代码,以便将其添加到我的响应中?

我发现它exception.getFieldError().getArguments()包含一个数组,其中包含我想要的值,SpringValidatorAdapter.ResolvableAttribute但我不知道如何使用它。

标签: springspring-boot

解决方案


我能想到的最好的方法是将 ajavax.validation.Validator注入@RestControllerAdvice然后使用以下内容@ExceptionHandler来获取验证注释的“errorCode”值。

@ExceptionHandler({WebExchangeBindException.class})
Mono<ResponseEntity<...>> webExchangeBindException(WebExchangeBindException exception, ServerHttpRequest request) {
    Set<ConstraintViolation<Object>> violations = validator.validate(exception.getTarget());
    violations.stream()
        .findFirst()
        .ifPresent(violation -> /*Assign error here */ ... violation.getConstraintDescriptor().getAttributes().get("errorCode"));
    return ...;
}

这行得通,但我觉得应该有更好的方法来做到这一点。


推荐阅读