如何检查i18n消息资源参数是否为空?

tjjdgumg  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(420)

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

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

如果arguments数组为空,那么客户端不应该看到这样的消息
找不到{0}的产品
我想让用户看看这个
未找到产品。
我能那样做吗?

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

lc8prwob1#

我想你可以定义两个关键点:

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

然后用代码处理

6fe3ivhb

6fe3ivhb2#

为什么参数数组是空的?不能使用两个不同的键并提前检查以使用基于参数的正确消息吗?它们是两种不同的信息,应该有自己的密钥。
消息.属性

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类,特别是formatmessage和renderdefaultmessage方法。

相关问题