我遇到了类似的问题,最终扩展了 SpringValidatorAdapter 类,以便我可以执行验证并指定组。
ExtendedSpringValidatorAdapter adapter = new ExtendedSpringValidatorAdapter(validator);
adapter.validate(objectToValidate, bindingResult, Class1.class, Class2.class);
这是扩展验证器的定义:
package com.example.validator;
import org.springframework.beans.NotReadablePropertyException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
public class ExtendedSpringValidatorAdapter extends SpringValidatorAdapter {
// ========================================================================
// ========================================================================
// ========================================================================
public ExtendedSpringValidatorAdapter(Validator targetValidator) {
super(targetValidator);
}
// ========================================================================
// ========================================================================
// ========================================================================
public void validate(Object target, Errors errors, Class<?>... groups) {
if (groups == null || groups.length == 0 || groups[0] == null) {
groups = new Class<?>[]{Default.class};
}
Set<ConstraintViolation<Object>> result = validate(target, groups);
for (ConstraintViolation<Object> violation : result) {
String field = violation.getPropertyPath().toString();
FieldError fieldError = errors.getFieldError(field);
if (fieldError == null || !fieldError.isBindingFailure()) {
try {
errors.rejectValue(field,
violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
getArgumentsForConstraint(errors.getObjectName(), field, violation.getConstraintDescriptor()),
violation.getMessage());
} catch (NotReadablePropertyException ex) {
throw new IllegalStateException("JSR-303 validated property '" + field +
"' does not have a corresponding accessor for Spring data binding - " +
"check your DataBinder's configuration (bean property versus direct field access)", ex);
}
}
}
}
}