【问题标题】:Hibernate validation with custom messages in property file使用属性文件中的自定义消息进行休眠验证
【发布时间】:2015-08-11 20:41:35
【问题描述】:

您好,我在球衣休息服务中使用休眠验证器。 这里我们如何将值传递给属性文件消息如下

empty.check= Please enter {0} 

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

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

在{0}中我需要传递“用户名”,同样我需要重用消息

请帮我解决这个问题。

【问题讨论】:

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


    【解决方案1】:

    您可以通过更改注释来提供字段描述,然后在验证器中公开它来做到这一点。

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

    【讨论】:

    • @ beerbajay 感谢重播。但是如果消息中有多个参数,例如empty.check=请输入{0} {1}。我们怎样才能实现..?
    • @ShashiDk 你用不同的变量名多次调用addExpressionVariable。你从哪里得到这些参数?
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 2011-08-09
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2017-05-09
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多