I am trying to modify an existing Spring Boot application to support multilingual error messages. I have changed the annotation on the property as follows:
@Size(min = 2, max = 75, message = "Book.name.Size")
private String name;
My messages_en.properties looks like:
Book.name.Size = The name must be between {min} and {max} characters
The MessageSource config is as follows:
@Configuration
public class MessageSourceConfig extends WebMvcConfigurerAdapter {
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(600);
return messageSource;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);
return sessionLocaleResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
@Bean
public LocalValidatorFactoryBean validator()
{
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.setValidationMessageSource(messageSource());
return localValidatorFactoryBean;
}
}
If a value is entered that is too small/large the error message returned does not contain the interpolated min/max values so the user sees exactly:
The name must be between {min} and {max} characters
I tried changing the annotation on the property to include curly braces:
@Size(min = 2, max = 75, message = "{Book.name.Size}")
private String name;
But now I receive an error instead:
org.springframework.context.NoSuchMessageException: No message found under code 'The name must be between 2 and 75 characters' for locale 'en'
It must be an issue with the configuration but I don't know where the problem lies...
{min}and{max}use{0}and{1}. - M. DeinumThe name must be between {0} and {1} characters- smilin_stan