java 34 lines · 6 steps

Localized bean validation messages in Spring

Wire a custom MessageSource into Spring's validator so constraint messages are resolved from properties files per locale.

Explained by highlit
1@Configuration
2public class ValidationConfig implements WebMvcConfigurer {
3 
4 @Bean
5 public MessageSource messageSource() {
6 ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
7 source.setBasenames("classpath:messages/validation", "classpath:messages/labels");
8 source.setDefaultEncoding(StandardCharsets.UTF_8.name());
9 source.setFallbackToSystemLocale(false);
10 source.setUseCodeAsDefaultMessage(false);
11 source.setCacheSeconds(30);
12 return source;
13 }
14 
15 @Bean
16 public LocalValidatorFactoryBean localValidatorFactoryBean(MessageSource messageSource) {
17 LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
18 factory.setValidationMessageSource(messageSource);
19 return factory;
20 }
21 
22 @Bean
23 public LocaleResolver localeResolver() {
24 AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
25 resolver.setDefaultLocale(Locale.ENGLISH);
26 resolver.setSupportedLocales(List.of(Locale.ENGLISH, Locale.forLanguageTag("pt-BR"), Locale.GERMAN));
27 return resolver;
28 }
29 
30 @Override
31 public Validator getValidator() {
32 return localValidatorFactoryBean(messageSource());
33 }
34}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Feeding a MessageSource into the validator lets constraint messages come from your own properties files instead of hardcoded defaults.
  2. 2AcceptHeaderLocaleResolver picks the response locale from the request's Accept-Language header against a supported set.
  3. 3Turning off system-locale fallback and code-as-default forces missing keys to surface loudly during development.

Related explainers

typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
java
public static Map<String, String> parseCookieHeader(String header) {
    Map<String, String> cookies = new LinkedHashMap<>();
    if (header == null || header.isBlank()) {
        return cookies;

Parsing an HTTP Cookie header in Java

string-parsing http url-decoding
Intermediate 6 steps
java
public class TimedSocketReader {
 
    private static final int READ_TIMEOUT_MS = 5_000;
    private static final int CONNECT_TIMEOUT_MS = 3_000;

Reading a socket with connect and read timeouts

sockets timeouts io
Intermediate 8 steps
java
public final class EncodingDetector {
 
    public enum Encoding {
        UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN

Detecting text encoding from raw bytes in Java

byte-manipulation encoding-detection bitwise-operations
Intermediate 8 steps

Share this explainer

Here's the card — post it anywhere.

Localized bean validation messages in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code