为此,您只能使用类型级别注释,因为字段级别注释无法访问其他字段!
我做了一些类似的事情以允许选择验证(确切地说,许多属性之一必须不为null)。在您的情况下,
@AllOrNone注释(或您希望使用的任何名称)将需要一个字段名称数组,并且您将带注释类型的整个对象提供给验证器:
@Target(ElementType.TYPE)@Retention(RUNTIME)@documented@Constraint(validatedBy = AllOrNonevalidator.class)public @interface AllOrNone { String[] value(); String message() default "{AllOrNone.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};}public class AllOrNonevalidator implements ConstraintValidator<AllOrNone, Object> { private static final SpelexpressionParser PARSER = new SpelexpressionParser(); private String[] fields; @Override public void initialize(AllOrNone constraintAnnotation) { fields = constraintAnnotation.value(); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { long notNull = Stream.of(fields) .map(field -> PARSER.parseexpression(field).getValue(value)) .filter(Objects::nonNull) .count(); return notNull == 0 || notNull == fields.length; }}(正如您所说,您使用Spring时,我使用SpEL甚至允许嵌套字段访问)
现在您可以注释您的
Subscriber类型:
@AllOrNone({"birthday", "/confirm/iBirthday"})public class Subscriber { private String name; private String email; private Integer age; private String phone; private Gender gender; private Date birthday; private Date /confirm/iBirthday; private String birthdayMessage; private Boolean receiveNewsletter;}


