我的Spring应用程序以3种配置运行:
如何才能进入应用程序正在运行的晶闸管环境?
我需要包括谷歌分析代码仅在生产环境。
发布于 2014-05-17 13:47:03
如果一次只有一个概要文件处于活动状态,则可以执行以下操作。
<div th:if="${@environment.getActiveProfiles()[0] == 'production'}">
This is the production profile - do whatever you want in here
</div>上面的代码基于这样一个事实:Thymeleaf的Spring方言允许您使用@符号访问bean。当然,Environment对象始终可以作为Spring使用。
还请注意,Environment有一个方法getActiveProfiles(),它返回一个Spring数组(这就是为什么在我的答案中使用[0] ),我们可以使用标准Spring调用它。
如果一次有多个概要文件处于活动状态,则更健壮的解决方案是使用Thymeleaf的#arrays实用程序对象,以检查活动配置文件中是否存在字符串production。这种情况下的守则是:
<div th:if="${#arrays.contains(@environment.getActiveProfiles(),'production')}">
This is the production profile
</div>发布于 2019-08-21 13:31:57
只需添加这个类就可以为视图设置全局变量:
@ControllerAdvice
public class BuildPropertiesController {
@Autowired
private Environment env;
@ModelAttribute("isProd")
public boolean isProd() {
return Arrays.asList(env.getActiveProfiles()).contains("production");
}
}然后在您的胸腺网文件中使用${isProd}变量:
<div th:if="${isProd}">
This is the production profile
</div>也可以将活动概要文件名设置为全局变量:
@ControllerAdvice
public class BuildPropertiesController {
@Autowired
private Environment env;
@ModelAttribute("profile")
public String activeProfile() {
return env.getActiveProfiles()[0];
}
}然后在您的胸腺网文件中使用${profile}变量(如果您有一个活动配置文件):
<div>
This is the <span th:text="${profile}"></span> profile
</div>https://stackoverflow.com/questions/23711541
复制相似问题