Gau*_*rav 6 java spring internationalization spring-boot
我正在使用 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>
Run Code Online (Sandbox Code Playgroud)
@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;
}
Run Code Online (Sandbox Code Playgroud)
下面是我的 restcontroller 类方法:
@GetMapping("/hello-world-I18N")
public String helloWorldI18N(@RequestHeader(name="Accept-Language",required = false) Locale locale) {
return messageSource.getMessage("good.morning.message",null,locale);
}
Run Code Online (Sandbox Code Playgroud)
在调试日志中自动配置不匹配。
MessageSourceAutoConfiguration: 不匹配: - ResourceBundle 没有找到带有基本名称消息的包 (MessageSourceAutoConfiguration.ResourceBundleCondition)
我确实尝试过检测到配置中的另一种方式,但错误与突出显示的错误相同。
@Bean
public MessageSource resourceBundleMessageSource() {
ReloadableResourceBundleMessageSource resourceBundleMessageSource = new ReloadableResourceBundleMessageSource ();
resourceBundleMessageSource.setBasename("messages");
return resourceBundleMessageSource;
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
messages.properties 的内容:good.morning.message=早上好
与其他版本一样,这是当前 Spring Boot 2.1.1.RELEASE 的问题吗???
来自Spring 文档:
加载 ApplicationContext 时,它会自动搜索上下文中定义的 MessageSource bean。bean 必须具有名称 messageSource。
因此,仅使用名称定义的ApplicationContext期望MessageSourcebean messageSource。
当前 Spring bootMessageSourceAutoConfiguration与此策略不一致:messageSource如果找到带有MessageSourceclass的 bean,它不会公开bean 。
所以你的问题的解决方案是:
将方法名称更改为messageSource:
@Bean
public MessageSource messageSource()
Run Code Online (Sandbox Code Playgroud)
或者显式地向 bean 添加名称:
@Bean("messageSource")
public MessageSource resourceBundleMessageSource()
Run Code Online (Sandbox Code Playgroud)
Spring Boot 中的行为将在 2.2.x 中改变。如果找不到bean 的名称而不是类,MessageSourceAutoConfiguration则将公开。MessageSourcemessageSource
请参阅此拉取请求。(免责声明:我是公关的作者)
| 归档时间: |
|
| 查看次数: |
4642 次 |
| 最近记录: |