2015-05-29 48 views
2

您好在球衣休息服务中使用hibernate验证器。 在这里,我们如何能够及格的价值属性文件消息在属性文件中使用自定义消息进行休眠验证

empty.check= Please enter {0} 

这里{0}我需要从注释

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

在这里传递值{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 

当用户名为空或空这将产生以下错误:

Please enter a user name 
+0

@ beerbajay感谢重播。但是,如果消息中有多个参数,例如empty.check =请输入{0} {1}。我们如何实现..? –

+0

@ShashiDk您可以使用不同的变量名称多次调用'addExpressionVariable'。从哪里获取这些参数? – beerbajay