自定义验证注释应该不是问题:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotEmptyFieldsValidator.class)
public @interface NotEmptyFields {
String message() default "List cannot contain empty fields";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
public class NotEmptyFieldsValidator implements ConstraintValidator> {
@Override
public void initialize(NotEmptyFields notEmptyFields) {
}
@Override
public boolean isValid(List objects,ConstraintValidatorContext context) {
return objects.stream().allMatch(nef -> nef != null && !nef.trim().isEmpty());
}
}
用法?简单:
class QuestionPaper{
@NotEmptyFields
private List questionIds;
// getters and setters
}
附:没有测试逻辑,但我想这很好.