如何在Spring中使用自定义验证器时在错误消息中获取无效值?

时间:2013-11-22 14:00:50

标签: spring spring-mvc bean-validation hibernate-validator

我在错误消息中显示无效值时遇到问题 我有messages.properties文件如下

ProductId.exists.custom.validator.validation = A product already exists with product id ${validatedValue}.

以下是我的自定义验证器界面

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = ProductIdValidator.class)
@Documented
public @interface ProductId {
   String message() default "{ProductId.exists.custom.validator.validation}";

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

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

这是实施

@Component
public class ProductIdValidator implements ConstraintValidator<ProductId, String>{

    @Autowired
    private ProductService productService;

    @Override
    public void initialize(ProductId constraintAnnotation) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Product product = productService.getProductById(value);
        if(product!= null) {
            return false;
        }
        return true;
    }

}

当我运行我的应用程序时,我收到错误信息 A product already exists with product id ${validatedValue}.但我希望A product already exists with product id P1234.为错误消息

如何在错误消息中获取validatedValue?

其他详细信息 我使用了hibernate-validator:4.3.1.Final版本和spring-webmvc:3.2.0.RELEASE 我在上下文中触发验证如下

<mvc:annotation-driven validator="validator"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource" />
</bean>

1 个答案:

答案 0 :(得分:1)

我不确定我在项目中使用此解决方案的主要原因是什么 - 如果要进行插值工作,或者只使用ReloadableResourceBundleMessageSource(支持UTF-8中的属性和运行时重新加载!而不是默认的。但是,这应该对你有用。

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" primary="true"
      p:messageInterpolator-ref="messageInterpolator" />

<!-- Hibernate Validator which can interpolate the value being validated in the constraint message -->
<bean id="messageInterpolator" class="ValueFormatterMessageInterpolatorFactoryBean"
      p:messageSource-ref="validatorMessageSource" />

<bean id="validatorMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
      p:basename="classpath:/config/i18n/validator-messages"
      p:defaultEncoding="utf-8"
      p:cacheSeconds="0" />

自定义ValueFormatterMessageInterpolatorFactoryBean类:

/**
 * {@linkplain FactoryBean} that creates {@link ValueFormatterMessageInterpolator}
 * with underlying {@link ResourceBundleMessageInterpolator} that uses the given
 * {@link MessageSource}.
 */
public class ValueFormatterMessageInterpolatorFactoryBean implements FactoryBean<MessageInterpolator> {

    private MessageSource messageSource;

    public MessageInterpolator getObject() throws Exception {
        ResourceBundleLocator resourceBundleLocator = new MessageSourceResourceBundleLocator(messageSource);
        return new ValueFormatterMessageInterpolator(
                new ResourceBundleMessageInterpolator(resourceBundleLocator));
    }

    public Class<?> getObjectType() {
        return ValueFormatterMessageInterpolator.class;
    }

    public boolean isSingleton() {
        return true;
    }

    @Required
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}

注意:我正在使用Hibernate Validator 4.3.0.Final。