从 Maven 配置文件激活 spring 引导配置文件

问题描述

我想将我的 junit 测试和集成测试分开。所以我在 pom.xml 中为集成测试创建了一个单独的配置文件,如下所示:

<profiles>
<profile>
    <id>integration-test</id>
    <properties>
        <test>IntegrationTestTrigger</test>
        <spring.profiles.active>integration-test</spring.profiles.active>
    </properties>
</profile>                                                                                  
<profiles>

当我运行 maven 命令 mvn test -Pintegration-test 时,它会选择上面显示<properties> 标记中定义的测试类IntegrationTestTrigger。但它没有设置 spring.profiles.active 属性。所以测试从配置文件开始。它与 maven 命令 mvn test -Dtest=IntegrationTestTrigger -Dspring.profiles.active=integration-test

一起工作正常

但根据我的组织 jenkins 设置,我需要为集成测试运行 mvn test -Pintegration-test,因此我无法向 mvn 命令添加任何额外的环境变量

解决方法

中的属性用于替换资源文件夹中 .properties/.yml 文件中的属性。

示例:

application.yml:

spring:
   profiles:
       active: '@spring.profiles.active@'

pom.xml:

        <profile>
            <id>dev</id>
            <properties>
                <spring.profiles.active>dev</spring.profiles.active>
            </properties>
        </profile>

这里,@spring.profiles.active@ 将在编译期间被 dev 替换(通过 maven-resources-plugin 插件)。 Spring Boot 在 spring-boot-starter-parent pom 中使用 @ 作为资源分隔符。您可以通过更改以下属性将其更改为任何字符

//pom.xml
<project  .....>
  <properties>
    <resource.delimiter>@</resource.delimiter>
    ...
  </properties>

请参阅 https://github.com/gtiwari333/spring-boot-blog-app/blob/master/pom.xml#L436 以获取完整示例

另见:https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-automatic-expansion-maven