spring - 在 Spring Boot 和 Kotlin 中如何正确添加国际化?
问题描述
尽管我遇到了一些问题,但我一直在关注本教程并且可以遵循它。
几乎在最后,它谈到了配置属性,虽然尝试为它设置某种国际化是一个好主意,根据语言使用不同的文件,但我一直无法这样做。无论我如何尝试,我都只加载英语。
解决方案
您是否阅读过有关国际化的 Spring Boot 文档?我想这不是很有帮助。
假设你有这样的资源包。
- src/main/resources/
- messages.properties
- messages_es.properties
- ...
您需要添加一些配置:
@Configuration
class AppConfig : WebMvcConfigurer {
@Bean
fun localeResolver() = SessionLocaleResolver().apply {
setDefaultLocale(Locale.ENGLISH)
}
@Bean
fun localeInterceptor() = LocaleChangeInterceptor().apply {
this.paramName = "lang"
}
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(localeInterceptor())
}
}
然后使用的示例greet.hello
可能如下所示:
import org.springframework.context.MessageSource
import org.springframework.context.i18n.LocaleContextHolder
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class PageController(val messageSource: MessageSource) {
@GetMapping("/greet")
fun greet(): String {
return messageSource.getMessage("greet.hello", null, LocaleContextHolder.getLocale())
}
}
如果您不认为这看起来很漂亮,那么请尝试使用 Kotlin 的一些功能来清理它。
这是选择语言的方法:
# Use the default
curl --request GET --url 'http://localhost:8080/greet'
# Hello
# Use English
curl --request GET --url 'http://localhost:8080/greet?lang=en'
# Hello
# Use Spanish
curl --request GET --url 'http://localhost:8080/greet?lang=es'
# Hola
推荐阅读
- alexa - Alexa 智能家居功能相互超越
- python - 我的 if 语句是错误的,但它确实打印了结尾
- r - 如何将 hjust 与 geom_text 一起使用?
- javascript - Spring RSocket Security + RSocket-WebSocket-Client(浏览器)
- azure - 从守护程序应用程序调用 Azure 中的 ASP .NET Core API
- python - 时间对象列表中的值显示为“时间”而不是 hh:mm:ss 格式
- java - Spark 未利用 GPU taskResourceAssignments Map(gpu -> [0]
- python - 如何在 Python 中从 txt 文件制作字典
- multithreading - 使用 vwait 的 Tcl 线程产生随机结果
- javascript - 在不使用 JQueryUI 的情况下限制可拖动的 div