我看到这样做的方式是使用标准的 JSR-303 验证器(无论你已经注入了什么)来获取违规行为(即Set<ConstraintViolaion<T>>
)
然后使用类似于 LocalValidatorFactoryBean 内部的代码在这些违规和 Spring 错误之间进行转换:
public static <T> void convert(Errors errors, Collection<ConstraintViolation<T>> violations) {
for (ConstraintViolation<?> violation : violations) {
String field = violation.getPropertyPath().toString();
FieldError fieldError = errors.getFieldError(field);
if (fieldError == null || !fieldError.isBindingFailure()) {
errors.rejectValue(field, violation.getConstraintDescriptor().getAnnotation().annotationType()
.getSimpleName(), getArgumentsForConstraint(errors.getObjectName(), field, violation
.getConstraintDescriptor()), violation.getMessage());
}
}
}
private static Object[] getArgumentsForConstraint(String objectName, String field,
ConstraintDescriptor<?> descriptor) {
List<Object> arguments = new LinkedList<Object>();
String[] codes = new String[] { objectName + Errors.NESTED_PATH_SEPARATOR + field, field };
arguments.add(new DefaultMessageSourceResolvable(codes, field));
arguments.addAll(descriptor.getAttributes().values());
return arguments.toArray(new Object[arguments.size()]);
}