加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Java/Spring中,如何优雅地处理缺失的翻译值?

发布时间:2020-12-15 01:49:39 所属栏目:大数据 来源:网络整理
导读:我正在使用Java Spring作为国际网站. 这两种语言是ZH和EN(中文和英文). 我有2个文件:messages.properties(用于英文键/值对)和messages_zh.properties. 该网站使用#springMessage标签以英文编码.然后我使用Poeditor.com让翻译人员为每个英语短语提供中文价值

我正在使用Java Spring作为国际网站.

这两种语言是ZH和EN(中文和英文).

我有2个文件:messages.properties(用于英文键/值对)和messages_zh.properties.

该网站使用#springMessage标签以英文编码.然后我使用Poeditor.com让翻译人员为每个英语短语提供中文价值.因此,尽管英语messages.properties文件总是完整的,虽然messages_zh.properties文件总是包含所有键,但messages_zh.properties文件有时会有空值,因为我几天后会收到翻译人员的翻译.

每当中文值丢失时,我都需要我的系统显示相当的英文值(在我的网站上).

如果没有中文价值,我如何告诉Spring“退回”使用英语?我需要在价值的基础上实现这一点.

现在,我在我的网站上看到空白按钮标签,只要缺少中文值.我宁愿在中文空白时使用英语(默认语言).

最佳答案
您可以为此创建自己的自定义消息源.

就像是:

public class SpecialMessageSource extends ReloadableResourceBundleMessageSource {

      @Override
      protected MessageFormat resolveCode(String code,Locale locale) {
         MessageFormat result = super.resolveCode(code,locale);
         if (result.getPattern().isEmpty() && locale == Locale.CHINESE) {
            return super.resolveCode(code,Locale.ENGLISH);
         }
         return result;
      }

      @Override
      protected String resolveCodeWithoutArguments(String code,Locale locale) {
         String result= super.resolveCodeWithoutArguments(code,locale);
         if ((result == null || result.isEmpty()) && locale == Locale.CHINESE) {
            return super.resolveCodeWithoutArguments(code,Locale.ENGLISH);
         }
         return result;
      }
   }

并在spring xml中配置此messageSource bean为

现在要解析Label,您将调用MessageSource的以下方法之一

String getMessage(String code,Object[] args,Locale locale);
String getMessage(String code,String defaultMessage,Locale locale);

当您的消息标签包含参数并且您通过args参数传递这些参数时,将调用resolveCode(),如下所示
invalid.number = {0}无效
并调用messageSource.getMessage(“INVALID_NUMBER”,新对象[] {2d},语言环境)

当您的消息标签没有参数并且将args参数传递为null时,将调用resolveCodeWithoutArguments()
validation.success =验证成功
并调用messageSource.getMessage(“INVALID_NUMBER”,null,locale)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读