【问题标题】:How can we use either of the validation in spring boot?我们如何在 Spring Boot 中使用任何一个验证?
【发布时间】:2020-09-29 19:28:24
【问题描述】:

我的 bean 中有两个变量,我希望填充 name 或 mobile,它们不能同时为 null。

@NotNull
private String name;

@NotNull
private String mobile;

我怎样才能做到这一点?

【问题讨论】:

标签: java mysql spring validation jpa


【解决方案1】:

您需要为此编写自定义注释并在类上使用

@AtLeastOneNotEmpty(fields = {"name", "phone"})
public class User{

自定义注解实现

@Constraint(validatedBy = AtLeastOneNotEmptyValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AtLeastOneNotEmpty {

  String message() default "At least one cannot be null";

  String[] fields();

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

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

自定义注解的验证器

public class AtLeastOneNotEmptyValidator
    implements ConstraintValidator<AtLeastOneNotEmpty, Object> {

  private String[] fields;

  public void initialize(AtLeastOneNotEmpty constraintAnnotation) {
    this.fields = constraintAnnotation.fields();
  }

  public boolean isValid(Object value, ConstraintValidatorContext context) {

    List<String> fieldValues = new ArrayList<String>();

    for (String field : fields) {
      Object propertyValue = new BeanWrapperImpl(value).getPropertyValue(field);
      if (ObjectUtils.isEmpty(propertyValue)) {
        fieldValues.add(null);
      } else {
        fieldValues.add(propertyValue.toString());
      }
    }
    return fieldValues.stream().anyMatch(fieldValue -> fieldValue!= null);
  }
}

【讨论】:

    【解决方案2】:

    您可以创建自己的验证或注释 试试这样:

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface NotNullConfirmed {
        String message() default "they can not be null";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    以及实现它的类:

       public class FieldConfirmedValidator implements ConstraintValidator<NotNullConfirmed, Object>{
        @Override
        public boolean isValid(Object user, ConstraintValidatorContext context) {
            String name = ((Your_bo)user).getName();
            String phone = ((Your_bo)user).getPhone();
            return !name.isEmpty() && !phone.isEmpty();
        }
    }
    

    并将此注释添加到您的班级

    @NotNullConfirmed 
    public class User{
    }
    

    【讨论】:

    • 你的验证器是如何与 Annotation 连接的,Your_bo 这里是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2018-06-28
    • 2019-10-16
    相关资源
    最近更新 更多