我正在使用 Spring Boot 2.1.1.RELEASE,但我无法访问已配置的消息源。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
@SpringBootApplication
public class RestfulWebservicesApplication {
//......... some code
//......... some code
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.US);
return resolver;
}
@Bean
public MessageSource resourceBundleMessageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource ();
resourceBundleMessageSource.setBasename("classpath:messages");
return resourceBundleMessageSource;
}
Above approach is from another SO question
下面是我的restcontroller类方法:
@GetMapping("/hello-world-I18N")
public String helloWorldI18N(@RequestHeader(name="Accept-Language",required = false) Locale locale) {
return messageSource.getMessage("good.morning.message",null,locale);
}
在调试日志中自动配置不匹配。
MessageSourceAutoConfiguration: Did not match: - ResourceBundle did not find bundle with basename messages (MessageSourceAutoConfiguration.ResourceBundleCondition)
我确实尝试了另一种检测到配置的方法,但错误与突出显示的相同。
@Bean
public MessageSource resourceBundleMessageSource() {
ReloadableResourceBundleMessageSource resourceBundleMessageSource = new ReloadableResourceBundleMessageSource ();
resourceBundleMessageSource.setBasename("messages");
return resourceBundleMessageSource;
}
MessageSourceAutoConfiguration:
Did not match:
- @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: current) found beans of type 'org.springframework.context.MessageSource' resourceBundleMessageSource (OnBeanCondition)
Matched:
- ResourceBundle found bundle URL [file:/C:/Users/gaura/IdeaProjects/restful-webservices/target/classes/messages.properties] (MessageSourceAutoConfiguration.ResourceBundleCondition)
messages.properties 的内容: good.morning.message=早上好
这是否是当前 Spring Boot 2.1.1.RELEASE 的问题,就像 other version 一样???
最佳答案
来自 Spring docs :
When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. The bean must have the name messageSource.
因此 ApplicationContext
期望 MessageSource
bean 仅使用 messageSource
名称定义。
当前 Spring boot 的 MessageSourceAutoConfiguration
与此策略不一致:如果找到具有 MessageSource
类的 bean,它不会公开 messageSource
bean。
所以解决你的问题是:
要么将方法名称更改为messageSource
:
@Bean
public MessageSource messageSource()
或者显式地为 bean 添加名称:
@Bean("messageSource")
public MessageSource resourceBundleMessageSource()
Spring Boot 中的行为将在 2.2.x 中发生变化。 MessageSourceAutoConfiguration
将公开 MessageSource
如果它不能通过名称而不是类找到 messageSource
bean。
参见 this拉取请求。 (免责声明:我是 PR 的作者)
关于java - 无法在 Spring Boot 2.1.1.RELEASE 中访问消息源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53968789/