温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot如何进行国际化支持

发布时间:2025-02-18 10:34:48 阅读:93 作者:小樊 栏目:软件技术
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Spring Boot 提供了对国际化的原生支持,可以通过以下步骤来实现:

  1. 添加依赖

pom.xml 文件中添加 spring-boot-starter-web 依赖(如果尚未添加):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 创建资源文件

src/main/resources 目录下创建一个名为 messages 的文件夹。在此文件夹中,为每种支持的语言创建一个属性文件。例如:

  • messages.properties (默认语言)
  • messages_en.properties (英语)
  • messages_zh_CN.properties (简体中文)

在这些文件中,添加键值对以表示翻译后的文本。例如,在 messages_en.properties 文件中:

greeting=Hello
welcome=Welcome to our application

messages_zh_CN.properties 文件中:

greeting=你好
welcome=欢迎使用我们的应用程序
  1. 配置国际化资源文件

application.propertiesapplication.yml 文件中,配置国际化资源文件的名称和位置。例如:

spring.messages.basename=messages/messages
  1. 使用国际化消息

在代码中使用 @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 端点时,应用程序将根据用户的语言环境返回相应的翻译文本。

  1. 设置默认语言

如果需要设置默认语言,可以在 application.propertiesapplication.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元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×