2
votes

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...

1
Instead of {min} and {max} use {0} and {1}. - M. Deinum
I tried this but the response is now The name must be between {0} and {1} characters - smilin_stan

1 Answers

0
votes

You have to add the following to your GreetingController :

@Autowired
private LocalValidatorFactoryBean validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}