使用 javax.validation 进行自定义验证

Jac*_*ada 2 java validation spring

我正在尝试制作自定义 java 验证注释并返回给我

请求处理失败;嵌套异常是 javax.validation.ConstraintDeclarationException:HV000144:交叉参数约束 com.my.company.CustomConstraint 非法放置在字段“private java.util.List com.my.company.ElementOfTheList”上。

代码真的很幼稚

@Documented
@Retention(RUNTIME)
@Target({ FIELD, METHOD})
@Constraint(validatedBy = ConstraintValidation.class)
public @interface CustomConstraint {

    String message() default "this is the default message";

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

    Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class ConstraintValidationimplements ConstraintValidator<CustomConstraint , List<ElementOfTheList>> {

    public boolean isValid(List<ElementOfTheList> value, ConstraintValidatorContext context) {
        System.out.println("only a sysout to test");
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

在其余的对象模型中

  @JsonProperty("ElementOfTheList")
  @Valid
  @NotNull(message ="not null message")
  @NotEmpty(message = "not empty message")
  @CustomConstraint 
  private List<ElementOfTheList> list = null;
Run Code Online (Sandbox Code Playgroud)

小智 5

改变

@SupportedValidationTarget(ValidationTarget.PARAMETERS)
Run Code Online (Sandbox Code Playgroud)

@SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)
Run Code Online (Sandbox Code Playgroud)

因为您想要验证元素(这里是 List 列表)而不是方法或构造函数的参数