Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom validation messages in Hibernate + Spring

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

But still just getting {location.title.notEmpty} as output instead of the 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's going wrong here?

like image 825
dtrunk Avatar asked Feb 10 '12 17:02

dtrunk


People also ask

How do I use message properties in spring boot?

Adding Message Properties Into The Spring Boot Project In order to do that, just create two files in src/main/resources/messages folder with naming as below, api_error_messages. properties. api_response_messages.

What is custom validation in spring boot?

A custom validation annotation can also be defined at the class level to validate more than one attribute of the class. A common use case for this scenario is verifying if two fields of a class have matching values.


1 Answers

Got it! :-)

I added the following bean instead the above mentioned two into 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 guess this is the reason: I used the Hibernate validation annotations (not the javax ones)

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

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

Hope this helps some other people out there ;-)

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

like image 179
dtrunk Avatar answered Oct 13 '22 03:10

dtrunk