Sub topic 10
Customizing and externalizing messages
Every failed constraint produces a message string. This chapter covers where that string comes from, how to change it, and how to move it out of your Java code into properties files that can be translated per request. It assumes you have already built the CreateUserRequest DTO, the @Valid controller, and the @RestControllerAdvice that returns a ProblemDetail with an errors map.
Where default messages come from
Each standard constraint has a default message. @NotBlank says "must not be blank" and @Min(18) says "must be greater than or equal to 18". Hibernate Validator ships these texts in a built-in bundle that is translated into many languages. The language is chosen from the request locale, which Spring MVC reads from the Accept-Language header.
So even without any configuration, a request with Accept-Language: de gets German default messages. You only need your own messages when the defaults are too generic or when they don't use your product's wording.
Inline messages and placeholders
Every constraint annotation has a message attribute. The simplest customization is a literal string:
@NotBlank(message = "Please enter your name")
String nameLiteral strings are fast to write, but they cannot be translated and they scatter user-facing text through your code. A message can also contain placeholders. These are resolved when validation runs, not when the annotation is compiled.
| Syntax | Meaning | Example |
|---|---|---|
| `{key}` | A message key looked up in a bundle, or an attribute of the constraint | `{user.name.required}`, `{max}` |
| `${expression}` | An expression evaluated with Jakarta Expression Language | `${validatedValue}` |
| `\{`, `\}`, `\$`, `\\` | Escapes for literal braces, dollar signs, and backslashes | `\{literal\}` |
The attribute names are the ones on the annotation. @Size(max = 50) exposes {max} and {min}, and @Min(18) exposes {value}. The variable validatedValue is always available in expressions.
@Size(max = 50, message = "Name must be at most {max} characters, but was ${validatedValue.length()}")
String nameExpressions need an Expression Language implementation on the classpath. spring-boot-starter-validation brings one in (tomcat-embed-el), so this works without extra setup.
Externalizing messages
Instead of text, put a key in braces in the message attribute. Then define the text in src/main/resources/messages.properties, which Spring Boot already reads as its MessageSource (the spring.messages.basename property defaults to messages).
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank(message = "{user.name.required}")
@Size(max = 50, message = "{user.name.size}")
String name,
@NotBlank(message = "{user.email.required}")
@Email(message = "{user.email.invalid}")
String email,
@NotNull(message = "{user.age.required}")
@Min(value = 18, message = "{user.age.min}")
Integer age) {
}user.name.required=Name is required
user.name.size=Name must be at most {max} characters
user.email.required=Email is required
user.email.invalid=Email must be a valid address
user.age.required=Age is required
user.age.min=You must be at least {value} years oldNotice that {max} and {value} still work inside the properties file. The key is resolved first, and the attribute placeholders in the resulting text are resolved afterward.
Your handler from the previous chapter needs no change. error.getDefaultMessage() already returns the interpolated text, because interpolation happens inside the validator, before the exception is thrown. A request with a blank name now returns:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"instance": "/users",
"errors": { "name": "Name is required" }
}How a message is resolved
The diagram shows the lookup order for one message template.
Spring Boot wires the auto-configured validator to the application's MessageSource, so keys in messages.properties are tried first. Hibernate Validator's own ValidationMessages.properties file also still works. Choose one location for your own keys, and prefer messages.properties so that validation text lives with the rest of your application messages.
Translating per locale
Add one file per language, named with the locale suffix. The German file below uses the same keys as the base file.
# messages_de.properties
user.name.required=Name ist erforderlich
user.name.size=Der Name darf höchstens {max} Zeichen lang sein
user.email.required=E-Mail ist erforderlich
user.email.invalid=Bitte eine gültige E-Mail-Adresse angeben
user.age.required=Alter ist erforderlich
user.age.min=Sie müssen mindestens {value} Jahre alt seinSpring reads messages*.properties as UTF-8 by default, so umlauts can be written directly. A request with Accept-Language: de now returns the German text, and any other language falls back to messages.properties.
Check the result with a MockMvc test. It assumes the UserController and ApiExceptionHandler from earlier chapters.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(UserController.class)
class LocalizedMessagesTest {
@Autowired
MockMvc mockMvc;
@Test
void returnsGermanMessageForGermanLocale() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.header("Accept-Language", "de")
.content("""
{"name":"","email":"[email protected]","age":30}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.name").value("Name ist erforderlich"));
}
}Locale fallback
Java's resource bundle lookup tries the requested locale, then the JVM's default locale, and only then the base file. If the server runs with a French default locale and you have a messages_fr.properties, a request for Spanish gets French text, not the base English. To make the base file the fallback, set this in application.properties:
spring.messages.fallback-to-system-locale=falseMessages for custom constraints
A custom constraint should follow the same pattern. Give its message default a namespaced key, and ship the text in the properties file.
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AllowedCountryValidator.class)
public @interface AllowedCountry {
String message() default "{com.example.validation.AllowedCountry.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}com.example.validation.AllowedCountry.message=Country ${validatedValue} is not supportedCallers can still override the default at the usage site with @AllowedCountry(message = "{checkout.country.unsupported}"). Using the fully qualified annotation name as the key prefix avoids collisions with keys from other libraries.
Building messages inside a validator
Sometimes the text depends on logic, for example a cross-field validator that reports which field is wrong. Inside isValid you can replace the default message with a new template:
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("{checkout.country.unsupported}")
.addConstraintViolation();Pass a key or a fixed string as the template, never text built from request data.
Common errors
- Braces appear in the response. A response like
"name": "{user.name.requird}"means the key was not found. Check for a typo, a missingmessages.propertieson the classpath, or aspring.messages.basenamethat does not match the file name. - Properties are not picked up in tests. Slice tests such as
@WebMvcTeststill load message sources, but a plainValidation.buildDefaultValidatorFactory()does not know about Spring'sMessageSource. In that case onlyValidationMessages.propertiesis read. {or$in a literal message disappears or fails. Escape these characters with a backslash. In a properties file, write\\{where the interpolator needs to see\{.- Different messages for the same field in the same request. Each failed constraint gives its own message, and the handler from the earlier chapter keeps only the first with
putIfAbsent. Order is not guaranteed. If the order matters, group the rules or change the handler to collect a list. - Clients need stable identifiers. Translated text is a bad contract for client logic. Return
error.getCode()(for exampleNotBlank) in addition to the message, and let clients branch on the code.
Exercise
A request with Accept-Language: es returns English text, and you expected it to return the base messages.properties text. But a request with Accept-Language: fr returns French. The server's JVM runs with the default locale fr_FR and you have a messages_fr.properties. Why does this happen, and what is the fix?
Show answer
Resource bundle lookup falls back to the JVM's default locale before it uses the base file. Since no messages_es.properties exists, Spain's request resolves to the system locale fr_FR, which finds messages_fr.properties. Set spring.messages.fallback-to-system-locale=false so a missing locale goes straight to messages.properties.
Exercise
Write the annotation attribute and properties entry so that @Size(min = 3, max = 20) on a username field reports "Username must be between 3 and 20 characters" without hard-coding the numbers in the text.
Show answer
Annotation: @Size(min = 3, max = 20, message = "{user.username.size}"). Properties entry: user.username.size=Username must be between {min} and {max} characters. The {min} and {max} placeholders are filled from the annotation's attributes, so changing the limits in the annotation updates the message.