我正在尝试修改现有的Spring Boot应用程序以支持多语言错误消息。我已经更改了属性的注释,如下所示:
@Size(min = 2, max = 75, message = "Book.name.Size")
private String name;
我的messages_en.properties
看起来像是:
Book.name.Size =名称必须介于{min}和{max}个字符
之间
MessageSource配置如下:
@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;
}
}
如果输入的值太小/太大,则返回的错误消息不包含插值的最小值/最大值,因此用户可以看到:
名称必须介于{min}和{max}个字符
之间
我尝试更改属性上的注释以包含花括号:
@Size(min = 2, max = 75, message = "{Book.name.Size}")
private String name;
但现在我收到了错误:
org.springframework.context.NoSuchMessageException:在代码''名称必须介于2到75个字符之间'找不到代码'en'
这一定是配置问题,但我不知道问题出在哪里......
答案 0 :(得分:0)
您必须将以下内容添加到GreetingController
:
@Autowired
private LocalValidatorFactoryBean validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}