在thymeleaf中获得Spring应用程序环境 [英] Get spring application environment in thymeleaf

查看:349
本文介绍了在thymeleaf中获得Spring应用程序环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Spring Boot应用程序以3种配置运行:

My Spring Boot application runs with 3 configurations:

  • application.properties->用于开发环境
  • application-test.properties->用于测试环境
  • application-production.properties->用于生产环境

如何在百里香环境中运行应用程序?

How is it possible to get in thymeleaf environment the application is running?

我只需要在生产环境中包括Google Analytics(分析)代码.

I need to include the Google Analytics code only in production environment.

推荐答案

如果一次只有一个配置文件处于活动状态,则可以执行以下操作.

You can do the following if you only have one profile active at a time.

<div th:if="${@environment.getActiveProfiles()[0] == 'production'}">
  This is the production profile - do whatever you want in here
</div>

以上代码基于Thymeleaf的Spring方言允许您使用@符号访问bean的事实.当然,Environment对象始终可以作为Spring bean使用.

The code above is based on the fact that the Thymeleaf's Spring dialect lets you access beans using the @ symbol. And of course the Environment object is always available as a Spring bean.

还请注意,Environment具有方法getActiveProfiles(),该方法返回一个字符串数组(这就是为什么在我的答案中使用[0]的原因),我们可以使用标准Spring EL进行调用.

Also note that Environment has the method getActiveProfiles() which returns an array of Strings (that is why [0] is used in my answer) which we can call using standard Spring EL.

如果一次有多个配置文件处于活动状态,则更可靠的解决方案是使用Thymeleaf的#arrays实用程序对象,以检查活动配置文件中是否存在字符串production.在这种情况下,代码将是:

If more than one profiles are active at a time, a more robust solution would be to use Thymeleaf's #arrays utility object in order to check for the presence of the string production in the active profiles. The code in that case would be:

<div th:if="${#arrays.contains(@environment.getActiveProfiles(),'production')}">
     This is the production profile
</div>

这篇关于在thymeleaf中获得Spring应用程序环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆