【问题标题】:How to check i18n message resource arguments is empty or not?如何检查 i18n 消息资源参数是否为空?
【发布时间】:2021-03-12 06:55:21
【问题描述】:

我的意思是,例如,这是我的 messages.properties 文件:

BFF.ERROR.PRODUCT_NOT_FOUND = Product with {0} not found

如果参数数组为空,我想这样做,客户端不应该看到这样的消息

未找到 {0} 的产品

我想让用户看到这个

找不到产品。

我可以这样做吗?

BFF.ERROR.PRODUCT_NOT_FOUND = Product with {0} not found | Product not found

【问题讨论】:

    标签: java spring spring-boot internationalization


    【解决方案1】:

    我想你可以定义两个键:

    BFF.ERROR.PRODUCT_NOT_FOUND = Product with {0} not found 
    BFF.NULL.PRODUCT_NOT_FOUND = Product not found
    
    

    然后在代码中处理

    【讨论】:

      【解决方案2】:

      为什么参数数组是空的?您不能使用两个不同的键并提前检查以根据参数使用正确的消息吗?它们是两条不同的消息,应该有自己的密钥。

      messages.properties

      key1=message with argument {0}
      key2=message without argument
      

      代码中的某处

      final String msg;
      if (condition) {
          msg = ... // if you have the argument for placeholder {0}, get message for key1
      } else {
          msg = ... // fallback, get message for key2
      }
      

      如果你真的想要,你可以考虑创建一个自定义消息源和/或支持 bean 并在那里处理这种事情,但这似乎比它的价值更麻烦。在这种情况下,请查看 Spring 提供的 MessageSourceSupport 类,特别是方法 formatMessagerenderDefaultMessage

      【讨论】:

        猜你喜欢
        • 2017-10-17
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 2016-03-28
        • 2019-01-03
        • 1970-01-01
        • 2014-07-04
        相关资源
        最近更新 更多