你需要註釋@Validated
。例如:
public class Foo {
@NotNull(groups = {AtLeastOne.class})
private Bar b1;
@NotNull(groups = {AtLeastTwo.class})
private Bar b2;
@NotNull(groups = {AtLeastThree.class})
private Bar b3;
}
@Validated(value=AtLeastOne.class)
將驗證只B1 @Validated(value=AtLeastTwo.class)
將驗證只B2
UPDATE
@NotAllNull(value={"b1", "b2", "b3"})
public class Foo {
private Bar b1;
private Bar b2;
private Bar b3;
}
@Documented
@Constraint(validatedBy = NotAllNullValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface NotAllNull {
String[] value;
}
public class NotAllNullValidator implements ConstraintValidator<NotAllNull, Object> {
private String[] fields;
@Override
public void initialize(final NotAllNull constraintAnnotation) {
fields = constraintAnnotation.value();
}
@Override
public boolean isValid(final Object instance, final ConstraintValidatorContext context) {
boolean result = false;
for(int i = 0 ; i < fields.length; i++) {
result |= org.apache.commons.beanutils.BeanUtils.getProperty(instance, fields[i])!=null;
}
return result;
}
}
我沒有IDE這裏,可能有些錯誤代碼,但希望你可以看到代碼背後的想法
沒有HibernateValidator,但是是JSR 303. – ricardoespsanto