【发布时间】:2016-12-24 17:06:20
【问题描述】:
我在使用带有 Kotlin 的 Spring Boot 来处理语言环境时遇到了一些麻烦。我在 application.properties 文件中创建了这些设置:
spring.messages.basename=messages/messages
spring.messages.cache-seconds=-1
spring.messages.encoding=UTF-8
然后在我的控制器中创建了一个自动装配的 MessageSource 实例:
@Autowired
lateinit var messageSource: MessageSource
当在 url 中放置一个语言环境作为参数时,当我调用 LocaleContextHolder.getLocale() 时,该参数似乎没有被拾取,所以它始终是 en_US。不过,我可以使用@RequestParam(value="locale") locale: Locale 作为我的控制器功能的参数手动将其拾取,并从那里在控制器功能中使用它,但不能在其他功能中使用。我认为 Spring Boot LocaleContextHolder 应该根据请求 URL 自动为整个会话保存当前语言环境。
我读过一篇较早的文章,其中提到在主类中使用 LocaleChangeInterceptor bean 以及 MessageSource 和 LocaleResolver bean,但另一篇文章说 Spring Boot 不需要。反正我试过了,没什么区别。这些是我使用的函数:
@Bean
open fun localeResolver(): LocaleResolver {
val slr = SessionLocaleResolver()
slr.setDefaultLocale(Locale.US)
return slr
}
@Bean
open fun localeChangeInterceptor(): LocaleChangeInterceptor {
val localeChangeInterceptor = LocaleChangeInterceptor()
localeChangeInterceptor.paramName = "locale"
return localeChangeInterceptor
}
@Bean
open fun messageSource(): ResourceBundleMessageSource {
val source = ResourceBundleMessageSource()
source.setBasenames("messages/messages")
source.setDefaultEncoding("UTF-8")
return source
}
除了手动捕获语言环境并将其作为控制器调用的每个函数中的参数之外,还有什么建议可以尝试吗?谢谢!
【问题讨论】:
标签: spring spring-boot internationalization locale kotlin