How to get the Invalid value in the error message while using custom validator in spring?

不打扰是莪最后的温柔 提交于 2019-12-02 12:59:01

I’m not sure what was the main reason for this solution I’ve used in my project – if to make interpolation work, or just use ReloadableResourceBundleMessageSource (that supports properties in UTF-8 and runtime reloading!) instead of the default one. However, this should work for you.

<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" />

And the custom ValueFormatterMessageInterpolatorFactoryBean class:

/**
 * {@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;
    }
}

Note: I’m using Hibernate Validator 4.3.0.Final.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!