Over a million developers have joined DZone.

Overriding Messages of Annotation-Based Validation in Spring

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

I was working on a project which is developed in Spring 3.0.

That project was almost completed and we have been using Annotation based validation for form fields mapped to that bean. We have been displaying messages to users by using annotation property “message.” Below is an example of it.

@Size(min = 1, max = 50, message = "Email size should be between 1 and 50")
private String loginId;

Now i have to shift all those error messages in properties files of all languages so that error messages will be loaded from properties files if user has changed the language.

Below are the steps of doing that.

@Size(min = 1, max = 50, message = "Email size should be between 1 and 50")
private String loginId;

Now remove { message = "Email size should be between 1 and 50" } from validation tag.

After doing this your annotation will be like this.

@Size(min = 1, max = 50)
private String loginId;

Now define this string in your properties file and a message against that string. Compile and execute. That message will be displayed whenever that annotation wouldn't be validated.

Size.loginForm.loginId=email shouldn't be empty.

This is the tricky part where I was making a mistake. Traditionally in properties file we will be defining the property name and a message against it.

loginForm.loginId=email shouldn't be empty.

But in annotations case Spring caters it differently. In this scenario spring makes its own string as key to its property file message if no error message has been given in annotation.

Below is the formula which spring uses to define a key of a property.

Size(@Size) = validation annotation name
loginForm = My Class Name
loginId = Property name in LoginForm class.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Shan Arshad, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}