首页 > 解决方案 > 如何将选定的 Maven 配置文件传递给 Spring 配置文件?

问题描述

我有 3 个 maven 项目 A、B、C。A 是 B 的父项目,B 是 C 的父项目。所有配置文件都在pom.xml项目 A中定义。

在项目 C 中,我试图根据所选配置文件在 spring-test-context (在src/test/resources下)中选择属性文件。对于回归测试,我们有 2 个属性文件:

在我们的 Windows 开发系统上,选定的配置文件将是“本地的”并相应地在服务器上。When "local" profile is selected, application-test-local.propertiesshould be used and application-test.propertiesotherwise in the test Spring context. 在项目 Cspring-test-context.xml,我尝试了:

<beans profile="docker">
    <util:properties id="metaDbProps"  location="application-test-local.properties"/>
 </beans>
 <beans profile="default">
    <util:properties id="metaDbProps"  location="application-test.properties"/>
 </beans>

但是,似乎应用程序无法将选定的 Maven 配置文件传递给 spring 配置文件,因为我正在尝试“mvn clean test -Pdocker”,并且它总是从“默认”配置文件中获取属性文件。

知道要修复什么以将 maven 配置文件传递给 spring 配置文件,以便它可以获取正确的属性文件吗?

为了便于理解,以下是项目 A 中配置文件的定义方式:

<profiles>
     <!-- Windows development  -->
    <profile>
        <id>docker</id>
        <activation/>
        <properties>
            <INSTALL_MACHINE_LIST>localhost</INSTALL_MACHINE_LIST>
            <COPY_MODE>local</COPY_MODE>
        </properties>
    </profile>
    <!-- Development -->
    <profile>
        <id>dev</id>
        <activation/>
        <properties>
            <INSTALL_MACHINE_LIST>dev01</INSTALL_MACHINE_LIST>
        </properties>
    </profile>
    <!-- QA -->
    <profile>
        <id>qa</id>
        <activation/>
        <properties>
            <INSTALL_MACHINE_LIST>dqa01</INSTALL_MACHINE_LIST>
        </properties>
    </profile>
    <!-- Production -->
    <profile>
        <id>prod</id>
        <activation/>
        <properties>
            <INSTALL_MACHINE_LIST>prod01</INSTALL_MACHINE_LIST>
        </properties>
    </profile>
</profiles>

标签: javaspringmaven

解决方案


默认情况下,Maven 测试使用Maven Surefire Plugin运行。您可以将 Spring 配置文件声明为 Maven 配置文件中的属性:

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

然后使用<argLine>配置将其传递给 Surefire:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <argLine>-Dspring.profiles.active=@{spring.profiles.active} @{argLine}</argLine>
      </configuration>
    </plugin>
  </plugins>
</build>

请注意@{...}语法:

由于 2.17 版使用 argLine 的替代语法,@{...} 允许在执行插件时延迟替换属性,因此已被其他插件修改的属性将被正确拾取


推荐阅读