首页 > 解决方案 > 在 Spring Boot 和 Kotlin 中如何正确添加国际化?

问题描述

尽管我遇到了一些问题,但我一直在关注教程并且可以遵循它。

几乎在最后,它谈到了配置属性,虽然尝试为它设置某种国际化是一个好主意,根据语言使用不同的文件,但我一直无法这样做。无论我如何尝试,我都只加载英语。

标签: springspring-bootkotlin

解决方案


您是否阅读过有关国际化的 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

推荐阅读