您可以通过更改注释来提供字段描述,然后在验证器中公开它来做到这一点。
首先,在注释中添加一个description 字段:
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EmptyCheckValidator.class)
@Documented
public @interface EmptyCheck {
String description() default "";
String message() default "{empty.check}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
接下来,更改您的消息,使其使用命名参数;这更具可读性。
empty.check= Please enter ${description}
由于您使用的是 hibernate-validator,因此您可以在验证类中获取 hibernate 验证器上下文并添加一个上下文变量。
public class EmptyCheckValidator
implements ConstraintValidator<EmptyCheck, String> {
String description;
public final void initialize(final EmptyCheck annotation) {
this.description = annotation.description();
}
public final boolean isValid(final String value,
final ConstraintValidatorContext context) {
if(null != value && !value.isEmpty) {
return true;
}
HibernateConstraintValidatorContext ctx =
context.unwrap(HibernateConstraintValidatorContext.class);
ctx.addExpressionVariable("description", this.description);
return false;
}
}
最后,在字段中添加描述:
@EmptyCheck(description = "a user name") private String userName
当 userName 为 null 或为空时,这应该会产生以下错误:
Please enter a user name