在Hibernate Validator中为每个属性生成错误代码

Mik*_*e Q 8 java validation hibernate-validator

我正在考虑使用Hibernate Validator来满足我的要求.我想验证一个JavaBean,其中属性可能有多个验证检查.例如:

class MyValidationBean
{
   @NotNull
   @Length( min = 5, max = 10 )
   private String myProperty;
}
Run Code Online (Sandbox Code Playgroud)

但是如果此属性验证失败,我想要一个特定的错误代码与ConstraintViolation相关联,无论它是否由于@Required或@Length而失败,尽管我想保留错误消息.

class MyValidationBean
{
   @NotNull
   @Length( min = 5, max = 10 )
   @ErrorCode( "1234" )
   private String myProperty;
}
Run Code Online (Sandbox Code Playgroud)

像上面这样的东西会很好,但它不一定要像那样结构.我看不到用Hibernate Validator做这个的方法.可能吗?

Ros*_*oss 5

您可以创建自定义注释以获取您要查找的行为,然后在验证和使用refelection时,您可以提取注释的值.类似于以下内容:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ErrorCode {
    String value();
}
Run Code Online (Sandbox Code Playgroud)

在你的bean中:

@NotNull
@Length( min = 5, max = 10 )
@ErrorCode("1234")
public String myProperty;
Run Code Online (Sandbox Code Playgroud)

在验证你的bean时:

Set<ConstraintViolation<MyValidationBean>> constraintViolations = validator.validate(myValidationBean);    
for (ConstraintViolation<MyValidationBean>cv: constraintViolations) {
    ErrorCode errorCode = cv.getRootBeanClass().getField(cv.getPropertyPath().toString()).getAnnotation(ErrorCode.class);
    System.out.println("ErrorCode:" + errorCode.value());
}
Run Code Online (Sandbox Code Playgroud)

话虽如此,我可能会质疑这些类型的消息需要错误代码的要求.


Pas*_*ent 3

来自 4.2 节。约束违反规范:

getMessageTemplate方法返回非插值错误消息(通常是message约束声明上的属性)。框架可以使用它作为错误代码键。

我认为这是你最好的选择。