我们如何在Spring Boot中使用任何一种验证? [英] How can we use either of the validation in spring boot?

查看:90
本文介绍了我们如何在Spring Boot中使用任何一种验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two variables in my bean and I want either name or mobile to be filled, they cant be both null at the same time.

@NotNull
private String name;

@NotNull
private String mobile;

我该如何实现?

推荐答案

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

You need to write a custom annotation for this and use on class

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

这篇关于我们如何在Spring Boot中使用任何一种验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆