title: Spring Boot validation - one from two not null
body: <p>I'm trying to validate if one of two fields are not null in Spring Boot?</p>
  
  <p>I have set that in the method class for the main object:</p>
  
  <pre><code>@NotNull(message = "Username field is required")
  private String username;
  
  @NotNull(message = "Email field is required")
  private String email;
  </code></pre>
  
  <p>but that will require to have both fields not null. Then I went with custom validation described here <a href="https://lmonkiewicz.com/programming/get-noticed-2017/spring-boot-rest-request-validation/" rel="noreferrer">https://lmonkiewicz.com/programming/get-noticed-2017/spring-boot-rest-request-validation/</a> but I wasn't able to get that example to work. I have to stuck on</p>
  
  <p>User class declaration:</p>
  
  <pre><code>@CombinedNotNull(fields = {"username","email"})
  public class User implements {
  
      private long id = 0L;
      @NotNull(message = "First name field is required")
      private String firstName;
  
      @NotNull(message = "Last name field is required")
      private String lastName;
  
      private String username;
      private String email;
  
      @NotNull(message = "Status field is required")
      private String status;
  
      ...all methods here...
      ...setters and getters...
  
  }
  </code></pre>
  
  <p>CombibnedNotNull class:</p>
  
  <pre><code>@Documented
  @Retention(RUNTIME)
  @Target({ TYPE, ANNOTATION_TYPE })
  @Constraint(validatedBy = userValidator.class)
  public @interface CombinedNotNull {
          String message() default "username or email is required";
          Class&lt;?&gt;[] groups() default { };
          Class&lt;? extends Payload&gt;[] payload() default { };
  }
  </code></pre>
  
  <p>userValidator class:</p>
  
  <pre><code>@Component
  public class userValidator implements ConstraintValidator&lt;CombinedNotNull, User&gt; {
  
      @Override
      public void initialize(final CombinedNotNull combinedNotNull) {
          fields = combinedNotNull.fields();
      }
  
      @Override
      public boolean isValid(final User user, final ConstraintValidatorContext context) {
          final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(user);
  
          for (final String f : fields) {
              final Object fieldValue = beanWrapper.getPropertyValue(f);
  
              if (fieldValue == null) {
                  return false;
              }
          }
  
          return true;
      }
  }
  </code></pre>
  
  <p>Is there any other way to get this done or should I go with the "complex" example from that page?</p>