Alex Rivera | Logout

Hibernate Validator, custom ResourceBundleLocator and Spring

Asked 2010-11-15T16:32:22.753
9

I'm trying to override default ResourceBundleLocator in hibernate validation 4.1. So far it works perfectly, but the only examples of its usage include java code to instantiate ValidationFactory.

When using a web application with spring hibernate validation is automatically configured (only the suitable hibernate validation *.jar file should exist and it is automatically used). How can i substitute ResourceBundleLocator in that scenario? I do not see any way of specyfing my custom ResourceBundleLocator in any properties or applicationContext.xml file.

Edit
Report

1 Answer

19

The magic method that does the required job is LocalValidatorFactoryBean#setValidationMessageSource(MessageSource messageSource).

First of all, contract of the method:-

Specify a custom Spring MessageSource for resolving validation messages, instead of relying on JSR-303's default "ValidationMessages.properties" bundle in the classpath. This may refer to a Spring context's shared "messageSource" bean, or to some special MessageSource setup for validation purposes only.

NOTE: This feature requires Hibernate Validator 4.1 or higher on the classpath. You may nevertheless use a different validation provider but Hibernate Validator's ResourceBundleMessageInterpolator class must be accessible during configuration.

Specify either this property or "messageInterpolator", not both. If you would like to build a custom MessageInterpolator, consider deriving from Hibernate Validator's ResourceBundleMessageInterpolator and passing in a Spring MessageSourceResourceBundleLocator when constructing your interpolator.

You can specify your custom message.properties(or .xml) by invoking this method... like this...

my-beans.xml

<bean name="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
        <ref bean="resourceBundleLocator"/>
    </property>
</bean>

<bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
      
answered 2010-11-22T16:13:44.863

Your Answer