Video in progress

Middle 🌱 Spring

What do you configure in Spring to return validation and business error messages in Uzbek, Russian and English?

The texts go into files like messages_uz.properties and messages_ru.properties, MessageSource reads them, and the language is determined from the Accept-Language header through a LocaleResolver. Bean Validation messages are also taken from these files in the {key} form.

📖 Answer

In Boot MessageSource is configured automatically, you only give the file name:

spring:
  messages:
    basename: i18n/messages
    encoding: UTF-8
    fallback-to-system-locale: false
# i18n/messages_uz.properties
order.notFound=Buyurtma topilmadi: {0}
product.name.required=Mahsulot nomi bo'sh bo'lmasligi kerak

In validation you put the key in curly braces:

record ProductRequest(@NotBlank(message = "{product.name.required}") String name) {}

Boot (since 2.6) connects the validator to the application's MessageSource, so the key is found in your files.

You translate business errors yourself inside the advice:

@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e, Locale locale) {
    String msg = messages.getMessage("order.notFound", new Object[]{e.id()}, locale);
    return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, msg);
}

The Locale parameter comes from the default AcceptHeaderLocaleResolver.

Problems that show up in practice: if fallback-to-system-locale stays on and the server is set to Russian, an unknown language gets Russian; keep the default language in messages.properties. If the file is saved in the IDE in an encoding other than UTF-8, words with apostrophes get garbled. And the ' character in a message is special for MessageFormat: in a message with parameters you have to write bo''sh with two apostrophes, otherwise {0} isn't substituted.