如何在Spring Boot中国际化特定的文本消息?

时间:2016-05-24 17:00:15

标签: java spring spring-boot internationalization

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

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

所以基本上我想要一个方法,用所需的本地化来记录一些消息的内容(" en"," fr"," es& #34;)并返回正确的字符串。另外,配置一些默认语言(例如" en")会很棒 - 如果不支持所需的语言,则可以使用它。

有关如何使用Spring Boot实现此目的的任何建议吗?

P.S。:对不起,是的,我已经尝试过"谷歌搜索"。我发现了几个国际化的例子,但大多数都没有用,因为它们是针对整个用户界面而不是特定的消息。

2 个答案:

答案 0 :(得分:4)

首先,您需要创建一些资源文件。在messages_en.properties中放置一个名为messages_fr.properties的文件和另一个名为src/main/resources的文件。

在en文件中放一行:

hello.world=Hello World!

在fr文件中添加一行:

hello.world=Bonjour le monde!

然后你需要在哪里得到这个文本注入一个MessageSource

@Autowired private MessageSource messageSource;

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

messageSource.getMessage("hello.world", null, locale);

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

答案 1 :(得分:0)

截至目前,我已经解决了手动初始化MessageSource的问题:

$to = "rahuldasgpta1000@gmail.com";
$subject = 'File Report On '.$date; 
 $txt = $body;

$headers= "MIME-Version: 1.0" . "\r\n";
$headers.= "Content-type:text/html;charset=UTF-8" . "\r\n";
//See the following line in your code you are missing '.' after $header
//Make sure concatenation is there.
$headers.= "From: surajbose@hotmail.com" . "\r\n" .
        "CC: rahul19832003@gmail.com"; 

自动装配使用空DelegatingMessageSource初始化我的messageSource,因此国际化不起作用。