我实现了自己的注释和 ConstraintValidator (JSR-303)。在验证过程中,我想创建不同的错误代码:
public class SomeValidator implements ConstraintValidator<ConstraintAnnotation,SomeObject> {
@Override
public void initialize (ConstraintAnnotation constraintAnnotation) {
}
@Override
public boolean isValid (SomeObject some, ConstraintValidatorContext context) {
int parameter = some.getParameter();
if (parameter==1){
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("SomeObject.code.first").addConstraintViolation();
return false;
}
if (parameter==2){
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("SomeObject.code.second").addConstraintViolation();
return false;
}
return true;
}
}
但是 context.buildConstraintViolationWithTemplate() 添加了错误消息而不是代码。所以弹簧关系来扩展这样的代码:
ConstraintAnnotation.someObject
不是
SomeObject.code.second
如何添加客户代码而不是消息?