提问者:小点点

我们如何在spring boot中使用这两种验证中的任何一种?


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

@NotNull
private String name;

@NotNull
private String mobile;

我怎么才能做到呢?


共2个答案

匿名用户

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

@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);
  }
}

匿名用户

您可以创建自己的验证或注释,请尝试如下所示:

@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 

公用类用户{}