Spring Boot 提供了对国际化的原生支持,可以通过以下步骤来实现:
在 pom.xml
文件中添加 spring-boot-starter-web
依赖(如果尚未添加):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在 src/main/resources
目录下创建一个名为 messages
的文件夹。在此文件夹中,为每种支持的语言创建一个属性文件。例如:
在这些文件中,添加键值对以表示翻译后的文本。例如,在 messages_en.properties
文件中:
greeting=Hello
welcome=Welcome to our application
在 messages_zh_CN.properties
文件中:
greeting=你好
welcome=欢迎使用我们的应用程序
在 application.properties
或 application.yml
文件中,配置国际化资源文件的名称和位置。例如:
spring.messages.basename=messages/messages
在代码中使用 @Autowired
注入 MessageSource
Bean,并使用 getMessage
方法获取国际化消息。例如:
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 GreetingController {
@Autowired
private MessageSource messageSource;
@GetMapping("/greeting")
public String greeting(Locale locale) {
return messageSource.getMessage("greeting", null, locale);
}
@GetMapping("/welcome")
public String welcome(Locale locale) {
return messageSource.getMessage("welcome", null, locale);
}
}
现在,当用户访问 /greeting
和 /welcome
端点时,应用程序将根据用户的语言环境返回相应的翻译文本。
如果需要设置默认语言,可以在 application.properties
或 application.yml
文件中配置 spring.messages.default-encoding
属性。例如:
spring.messages.default-encoding=UTF-8
spring.messages.locale=en
这将设置默认语言为英语。还可以通过在 URL 中添加 lang
参数来动态更改语言,例如:http://localhost:8080/greeting?lang=zh_CN
。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。