Use custom validation messages in Hibernate + Spring

I tried the steps from the answer here: Hibernate Validator, custom ResourceBundleLocator and Spring

But still just get {location.title.notEmpty} as an output instead of a message.

dispatcher-servlet.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"> <list> <value>/WEB-INF/validationMessages</value> </list> </property> </bean> 

/WEB-INF/validationMessages.properties:

 location.title.notEmpty=My custom message 

Form (class location)

 @NotEmpty( message = "{location.title.notEmpty}" ) private String title; 

What is wrong here?

+7
source share
1 answer

Got!: -)

I added the following bean instead of the above two in my dispatcher-servlet.xml :

  <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/validationMessages" /> </bean> 

Then in my validationMessages.properties I used the following syntax:

 NotEmpty.location.title=My custom Message 

I think this is the reason: I used Hibernate validation annotations (not javax)

And for the general syntax of the message file should look like

 [ConstraintName].[ClassName].[FieldName]=[Message] 

Hope this helps some other people ,-)

And to access the message from the spring controller, just add @Autowired private MessageSource messageSource; as a class field and use messageSource.getMessage methods. Since I use only one language, I used messageSource.getMessage( "NotEmpty.location.title", null, null )

+13
source

All Articles