我们如何在 Spring Boot 中使用任一验证?

2024-01-29

我的 bean 中有两个变量,我想要填写名称或手机,它们不能同时为空。

@NotNull
private String name;

@NotNull
private String mobile;

我怎样才能做到这一点?


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

@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);
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我们如何在 Spring Boot 中使用任一验证? 的相关文章

随机推荐