Java 如何访问 Thymeleaf 模板中的系统属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21726119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:21:01  来源:igfitidea点击:

How to access system properties in Thymeleaf template?

javaspringspring-mvcthymeleafspring-el

提问by junkie

I need to access system properties in a Thymeleaf template. It would be nice if this was possible so that I don't have to populate the spring mvc model explicitly with properties. I'm trying to use SPEL for this purpose but it's not working.

我需要访问 Thymeleaf 模板中的系统属性。如果这是可能的,那就太好了,这样我就不必用属性显式填充 spring mvc 模型。我正在尝试为此目的使用 SPEL,但它不起作用。

<h2 th:text="${ systemProperties['serverName'] }">Service name</h2>

<h2 th:text="*{ systemProperties['serverName'] }">Service name</h2>

Both of these give me:

这两个都给了我:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1012E:(pos 17): Cannot index into a null value

Even if I try to access a jdk property it gives the same error so I know it's not the fact that the property is missing. What am I doing wrong or is there another way to do this?

即使我尝试访问 jdk 属性,它也会给出相同的错误,所以我知道这不是缺少该属性的事实。我做错了什么还是有其他方法可以做到这一点?

采纳答案by Dave Bower

I use

我用

${@environment.getProperty('myPropertyName')}

回答by junkie

The link @Sudarshan_SMD posted gave me an idea and I finally got this to work as below.

@Sudarshan_SMD 发布的链接给了我一个想法,我终于让这个工作如下。

Put the following bean in your spring context.

将以下 bean 放入您的 spring 上下文中。

<bean id="sysprops" class="java.lang.System" factory-method="getProperties" />

Then access the bean directlyas follows in your thymeleaf template.

然后在您的 thymeleaf 模板中直接访问 bean,如下所示。

${@sysprops['yourPropertyName']}

This works because @sysprops allows direct access to the bean and the bean, which is java.lang.System, extends java.util.Hashtable and therefore allows key based access as opposed to function invocation based access. Doing it this way also means that you only have to define this bean once and use it across all your templates which is very convenient.

这是有效的,因为@sysprops 允许直接访问 bean,而 bean(java.lang.System)扩展了 java.util.Hashtable,因此允许基于键的访问,而不是基于函数调用的访问。这样做也意味着你只需要定义一次这个 bean 并在你的所有模板中使用它,这非常方便。