获得百里香的春季应用环境

occ*_*red 28 environment spring thymeleaf spring-boot

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

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

如何进入百里香叶环境应用程序正在运行?

我只需要在生产环境中包含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)

  • 同时在`Environment`中还有`acceptsProfiles(String ... profiles)`,这使得检查更平滑:`@ environment.acceptsProfiles('production')` (17认同)
  • 请注意 [`Environment.acceptsProfiles(String ...)`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html# AcceptProfiles(java.lang.String...)) 自 v5.1 起已被弃用。我已经打开了 [Issue #30206](https://github.com/spring-projects/spring-framework/issues/30206) 询问他们是否要重新考虑弃用,并让他们在这里进行讨论。 (2认同)

Igo*_*ock 5

只需添加此类即可为视图设置全局变量:

@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)