我正在使用带有自定义验证消息的 Spring Boot 创建一个 API,当我尝试从 messages.properties 文件获取消息时,我总是收到 org.springframework.context.NoSuchMessageException: No message found under code 'name.of.my.message' for locale 'en_US' 异常。
起初我以为是语言环境的问题,所以我尝试使用自己的 LocaleResolver @Bean 将默认语言环境设置为 US,并将 messages.properties 文件名更改为 messages_en_us.properties,但它并没有解决问题。
我最终认为可能是因为 messageSource 对象,我认为我是对的。当我调试时,我看到 messageSource 对象 的 parentMessageSource 为 null,当我进入 getMessage() 方法时,我看到如果 parentMessageSource 为 null,它将抛出 NoSuchMessageException。我没有找到很多关于这个具体问题的信息,这就是我在这里问这个问题的原因。
这是我在 application.java 中的代码(直到我使它工作):
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new
ResourceBundleMessageSource ();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
消息属性:
user.firstName.NotNull=First name must not be null.
从我读过的所有教程来看,这只是我获取验证消息所需的,但是,由于 ParentMessageSource 为 null,即使我的其余代码看起来没问题,也是不可能的。
最佳答案
好吧,我找到了解决方案。
其实很简单。我自己对 Spring boot 的误解就出在这里。基本上,在我的测试类中,我需要添加注释 @ConfigurationContext (classes = Application.java, MyCustomValidationConfig.java)
并且它有效!感谢所有看过的人。现在我只需要弄清楚测试@valid!
关于java - 如何修复 'parentMessageSource of the messageSourceBean' 使其不总是为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54595590/