我正在尝试从属性文件中读取错误消息,但我遇到此错误消息
org.springframework.context.NoSuchMessageException: No message found under code 'error.id.invalid' for locale 'en'.
我正在使用ResourceBundleMessageSource来设置基本名称
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("classpath:validations/messages.properties");
return messageSource;
}
这是我的异常处理程序
@Autowired
private ResourceBundleMessageSource messageSource;
@ExceptionHandler(value = {ConstraintViolationException.class})
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorMessageDTO handleResourceNotFoundException(ConstraintViolationException e) {
ErrorMessageDTO message = null;
if (e != null) {
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
StringBuilder strBuilder = new StringBuilder();
for (ConstraintViolation<?> violation : violations) {
Locale currentLocale = LocaleContextHolder.getLocale();
String msg = messageSource.getMessage(violation.getMessage(), null, currentLocale);
strBuilder.append(msg).append(", ");
}
message = new ErrorMessageDTO(MessageType.ERROR, strBuilder.toString(), BAD_REQUEST_ACTION, MODEL_INVALID_CODE);
try {
slf4jLogger.error(mapper.writeValueAsString(message));
} catch (JsonProcessingException ex) {
slf4jLogger.error(ex.getMessage());
}
}
return message;
}
这是我项目的目录结构
src
main
resources
validations
messages_en_US.properties
有人可以帮我弄清楚我错过了什么或做错了什么?
我知道有很多与此错误相关的问题,但没有一个解决方案适合我。任何帮助表示赞赏。
提前谢谢。
答案 0 :(得分:0)
这是提供ResourceBundleMessageSource
的方法。删除.properties
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("classpath:validations/messages");
return messageSource;
}
还尝试提供LocaleResolver。
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.ENGLISH);
return slr;
}