使用属性文件中的自定义消息进行Hibernate验证

时间:2015-05-29 05:33:32

标签: spring bean-validation jersey-2.0 hibernate-validator

您好在泽西休息服务中使用hibernate验证器。 我们如何将值传递给属性文件消息,如下所示

empty.check= Please enter {0} 

这里{0}我需要传递注释中的值

@EmptyCheck(message = "{empty.check}") private String userName

这里{0}我需要传递"用户名",同样我需要重复使用消息

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:3)

您可以通过更改注释来提供字段说明,然后在验证器中公开它。

首先,在注释中添加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