微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐