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?
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.
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With