如何使用属性节点在ConstraintValidator中动态插入消息?

时间:2017-08-02 13:52:53

标签: java hibernate bean-validation

假设我有一个字段的简单dto,并且这个dto也使用自定义验证注释进行注释:

@CustomAnnotation
public class SimpleDto {
    private String field;
}
// setters and getters omited

自定义注释:

@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
@Documented
public @interface CheckMondialRelayShopOrderWeight {
    String message() default "{temp.key.message}";

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

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

最后验证者本身:

public class CustomValidator implements
    ConstraintValidator<CustomAnnotation, SimpleDto> {
    @Override
    public void initialize(CustomAnnotation constraintAnnotation) {}

    @Override
    public boolean isValid(SimpleDto value, 
                        ConstraintValidatorContext context) {
        HibernateConstraintValidatorContext hibernateContext = context.unwrap(HibernateConstraintValidatorContext.class);
            hibernateContext.addMessageParameter("dynamicValue", 130);
            hibernateContext.buildConstraintViolationWithTemplate(hibernateContext.getDefaultConstraintMessageTemplate()).addPropertyNode("field").addConstraintViolation().disableDefaultConstraintViolation();
        return false;
    }
}

并在application.properties中:

CustomAnnotation.simpleDto.field=Your dynamic value is {dynamicValue}

但这不起作用,如果我放hibernateContext.buildConstraintViolationWithTemplate("Your dynamic value is {dynamicValue}").addConstraintViolation().disableDefaultConstraintViolation();代替hibernateContext.buildConstraintViolationWithTemplate(hibernateContext.getDefaultConstraintMessageTemplate()).addPropertyNode("field").addConstraintViolation().disableDefaultConstraintViolation();

我无法弄清楚如何使用addPropertyNode进行插值。有什么建议吗?

0 个答案:

没有答案