Spring Boot中如何将特定的短信国际化?

ste*_*pio 3 java spring internationalization spring-boot

目前我正在实施一项向客户发送通知(例如短信)的服务。服务是用 Java 编写的,基于 Spring Boot。

我想用收件人的语言发送消息。

所以基本上我想要一个方法,用所需的本地化(“en”,“fr”,“es”)获取消息的一些 id 并返回正确的字符串。还配置一些默认语言(如“en”)会很棒 - 如果不支持所需的语言,请回退到它。

任何建议如何使用 Spring Boot 实现这一目标?

PS:对不起,是的,我试过“谷歌搜索”。我找到了几个国际化示例,但其中大多数似乎没有用,因为它们是针对整个用户界面的,而不是针对特定消息的。

Ada*_*dam 6

首先,您需要创建几个资源文件。把一个名为messages_en.properties和另一个叫messages_fr.propertiessrc/main/resources

在 en 文件中放一行:

hello.world=Hello World!
Run Code Online (Sandbox Code Playgroud)

在 fr 文件中放一行:

hello.world=Bonjour le monde!
Run Code Online (Sandbox Code Playgroud)

然后在需要获取此文本的地方注入 MessageSource

@Autowired private MessageSource messageSource;
Run Code Online (Sandbox Code Playgroud)

然后你可以用它来获取文本

messageSource.getMessage("hello.world", null, locale);
Run Code Online (Sandbox Code Playgroud)

您需要将用户的语言环境传递给该方法。如果需要,您可以设置 LocaleResolver 来执行此操作。