SpringBoot项目如何国际化操作,让你可以随意切换语言
warning:
这篇文章距离上次修改已过417天,其中的内容可能已经有所变动。
Spring Boot 国际化操作通常涉及以下步骤:
- 在
src/main/resources目录下创建语言资源文件,例如:messages_en.properties(英文),messages_zh_CN.properties(中文简体)。 在资源文件中定义需要国际化的消息。例如,在中文简体资源文件中定义:
welcome.message=欢迎访问在英文资源文件中定义:
welcome.message=Welcome to- 在 Spring Boot 应用中配置国际化支持。这通常在
application.properties或application.yml文件中设置默认语言和国际化消息的基础名。 - 使用
MessageSource或@Autowired注入ResourceBundleMessageSource来获取国际化消息。
以下是一个简单的示例:
application.properties(配置默认语言和资源文件基础名)
spring.messages.basename=messages
spring.messages.encoding=UTF-8messages\_en.properties
welcome.message=Welcome tomessages\_zh\_CN.properties
welcome.message=欢迎访问Controller 示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
public class WelcomeController {
@Autowired
private MessageSource messageSource;
@GetMapping("/welcome")
public String welcomeMessage() {
return messageSource.getMessage("welcome.message", null, Locale.getDefault());
}
}当你访问 /welcome 端点时,它会根据请求的 Locale 返回相应的国际化消息。如果你想切换语言,你可以通过修改客户端请求的 Locale 来实现。在浏览器中,可以通过修改语言设置来实现。在程序中,可以通过设置 Locale.setDefault(Locale.US) 或 Locale.setDefault(Locale.SIMPLIFIED_CHINESE) 来切换语言。
评论已关闭