当在Java类上声明键时检索键的值

问题描述 投票:0回答:1

我正在使用弹簧腹板流量2.5.0和百里香叶3.0.9

我有一个包含一些静态键的类,例如:

public class MyKeys{
 .....
 public static final String myKey = "myKey1"
 .....  
}

在我的控制器的某个地方,我存储了该键的值,以便可以在模板文件中使用。

(伪代码):

context.add(MyKeys.mykey,"screen.home.welcome");

[screen.home.welcome是一个i18n消息密钥(存储在应用程序的message.properties上),其值我想提供给用户。

这有效但是我想使用MyKeys类中的键来访问其值。

<div th:utext="#{${myKey1}}"></div>

我尝试过的并且不是工作:

<div th:utext="#{${T(com.package.MyKeys).myKey}}"></div>

有了这个,我在模板中得到的是myKey1。我如何指示百里香叶检索与myKey1相关的值?

thymeleaf spring-webflow
1个回答
1
投票

您想要的间接级别有点奇怪...这不起作用的原因:

<div th:utext="#{${T(com.package.MyKeys).myKey}}"></div>
// Resolves to
<div th:utext="#{myKey1}"></div>
// Which isn't the actual message key since it's supposed to look like this:
<div th:utext="#{screen.home.welcome}"></div>

我可能不会推荐,但是您可以为此使用预处理。这样的事情可能会为您工作:

<div th:utext="#{${__${T(com.package.MyKeys).myKey}__}}"></div>
// Resolves to
<div th:utext="#{${myKey1}}"></div>
// Resolves to
<div th:utext="#{screen.home.welcome}"></div>

这可能也可以工作:

<div th:utext="#{${#root.get(T(com.package.MyKeys).myKey)}}"></div>
© www.soinside.com 2019 - 2024. All rights reserved.