occ*_*red 28 environment spring thymeleaf spring-boot
我的Spring Boot应用程序运行3个配置:
如何进入百里香叶环境应用程序正在运行?
我只需要在生产环境中包含Google Analytics代码.
geo*_*and 43
如果一次只有一个配置文件处于活动状态,则可以执行以下操作.
<div th:if="${@environment.getActiveProfiles()[0] == 'production'}">
This is the production profile - do whatever you want in here
</div>
Run Code Online (Sandbox Code Playgroud)
上面的代码基于以下事实:Thymeleaf的Spring方言允许您使用@符号访问bean .当然,该Environment对象始终可用作Spring bean.
另请注意,Environment有一个方法getActiveProfiles()可以返回一个字符串数组(这就是[0]我的答案中使用的原因),我们可以使用标准的Spring EL调用它.
如果一次有多个配置文件处于活动状态,则更强大的解决方案是使用Thymeleaf的#arrays实用程序对象来检查production活动配置文件中是否存在字符串.那种情况下的代码是:
<div th:if="${#arrays.contains(@environment.getActiveProfiles(),'production')}">
This is the production profile
</div>
Run Code Online (Sandbox Code Playgroud)
只需添加此类即可为视图设置全局变量:
@ControllerAdvice
public class BuildPropertiesController {
@Autowired
private Environment env;
@ModelAttribute("isProd")
public boolean isProd() {
return Arrays.asList(env.getActiveProfiles()).contains("production");
}
}
Run Code Online (Sandbox Code Playgroud)
然后${isProd}在 thymeleaf 文件中使用变量:
<div th:if="${isProd}">
This is the production profile
</div>
Run Code Online (Sandbox Code Playgroud)
或者您可以将活动配置文件名称设置为全局变量:
@ControllerAdvice
public class BuildPropertiesController {
@Autowired
private Environment env;
@ModelAttribute("profile")
public String activeProfile() {
return env.getActiveProfiles()[0];
}
}
Run Code Online (Sandbox Code Playgroud)
然后${profile}在 thymeleaf 文件中使用变量(如果您有一个活动配置文件):
<div>
This is the <span th:text="${profile}"></span> profile
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9347 次 |
| 最近记录: |