如何插入ConstraintValidator消息

时间:2019-01-23 02:41:38

标签: java hibernate-validator

我已经阅读了一些有关如何使用Hibernate的ConstrainValidator的问题解答和指南(例如Hibernate Documentation),但没有一个人清楚地提到如何在特定位置插入值验证错误消息。

例如,如果我有一个如下所示的验证错误消息:

foo.bar.error=This value '{value}' is wrong.

如果验证失败,我想获得以下消息:

  

“ some-value”值是错误的。

验证将像这样使用:

public class SomeClass {

    @SomeValidation(message="{foo.bar.error}")
    public SimpleDto someSimpleDto;

    ...

}

1 个答案:

答案 0 :(得分:1)

我找到了一种无需过多起毛即可内插消息的方法。

首先像以前一样设置ValidationMessages.properties(或存储验证消息的位置):

foo.bar.error=This value '{wrongValue}' is wrong.

像平常一样创建注释:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Constraint(validatedBy = CustomValueValidator.class)
@Target(FIELD)
@Retention(RUNTIME)
public @interface CustomAnnotation {    
    String message() default "{foo.bar.error}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

像这样实现约束验证器:

import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CustomValueValidator 
        implements ConstraintValidator<CustomAnnotation, SimpleDto> {

    @Override
    public void initialize(final CustomAnnotation constraintAnnotation) {
        // Extract any value you would need from the annotation
    }

    @Override
    public boolean isValid(final SimpleDto simpleDto, 
                           final ConstraintValidatorContext context) {
        boolean valid;

        // Some validations over the simpleDto

        if (!valid) {
            ((ConstraintValidatorContextImpl) context)
                    .addMessageParameter("wrongValue", simpleDto.toString());
        }

        return valid;
    }
}

现在剩下的就是使用注释:

public class SomeClass {

    // I'm using the default message. You could override it as a parameter
    @CustomAnnotation
    public SimpleDto someSimpleDto;

    ...

}