在Spring中,国际化(Internationalization)
和本地化(Localization)
是用来支持应用程序多语言的重要功能。国际化指的是设计应用程序以便能够轻松地支持多种语言和文化,而本地化则是根据用户的语言和文化习惯来显示相应的信息。
Spring提供了一套强大的国际化和本地化支持,其中主要使用 MessageSource
接口来加载不同语言的消息资源文件。
代码如下:
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Locale;
@Controller
public class HelloController {
private final MessageSource messageSource;
public HelloController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping("/hello")
@ResponseBody
public String hello() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("hello.message", null, locale);
}
}
HelloController 控制器,通过 MessageSource 接口来获取消息资源。在 hello 方法中,我们根据当前的 Locale
来获取对应的消息, hello.message
是消息资源文件中的键。
接下来,需要在Spring的配置文件中配置消息资源文件,例如 messages.properties
和 messages_zh_CN.properties
,分别存放英文和中文的消息内容:
messages.properties:
hello.message=Hello, World!
messages_zh_CN.properties:
hello.message=你好,世界!
通过这种方式,Spring会根据Locale 来加载对应的消息资源文件,从而实现国际化和本地化。当用户的语言设置为中文时,访问 /hello 端点会返回中文消息;当用户的语言设置为英文时,会返回英文消息。