首页 > 解决方案 > 使用 application.properties 文件为 Spring Boot 测试激活配置文件

问题描述

我一直在为我的测试框架使用 Spring Boot 和 TestNG,到目前为止,我的测试被配置为仅使用 src/main/resource 下的一个默认 application.properties 文件。现在我想为不同的环境配置它们 - ci/stage 等。我使用 spring 文档来激活 pom.xml 文件中的配置文件。

 <profiles>
    <profile>
        <id>ci</id>
        <properties>
            <activeProfile>ci</activeProfile>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
</profiles>

我在 src/main/resources 下有两个属性文件 - application.properties 和 application-ci.properties。(这是 spring 文档建议的命名约定。application-{activatedprofile}.properties)。

application.properties 有一个占位符 -

spring.profiles.active=@activeProfile@

@activeProfile@ 将被 pom.xml 文件中的 activeProfile 的值替换。并且直到它正在工作。

在我的@Configuration 类中,我有一个如下注释,我期望 ${spring.profiles.active} 值被替换为值 - ci。

 @PropertySource("classpath:application-${spring.profiles.active}.properties")

我收到以下错误:

java.lang.IllegalArgumentException: Could not resolve placeholder 
'spring.profiles.active' in value 
"classpath:application-${spring.profiles.active}.properties"

我正在使用 maven 和 testng 来运行我的项目。我在做一些不正确的事情,让我知道如何解决它。

标签: javaspringmavenspring-boottestng

解决方案


首先,maven profile和spring profile不一样。在提供的代码片段中,您正在设置 Maven 配置文件,而不是弹簧配置文件。

要在测试阶段传递特定的弹簧配置文件,您可以使用 surefire 插件。在下面的代码片段中,您将系统属性spring.profiles.active作为ci. 这相当于在application.properties文件中设置值。

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <configuration>
      <systemPropertyVariables>
        <spring.profiles.active>ci</spring.profiles.active>
      </systemPropertyVariables>
    </configuration>
  </plugin>

其次,spring 会根据激活的 spring 配置文件自动加载属性源。在您的示例中,弹簧将首先加载,application.properties然后将其应用application-ci.properties在其上。因此

@PropertySource("classpath:application-${spring.profiles.active}.properties")

不需要。

如果您有一个特定于活动配置文件的配置类,那么您可以添加@ActiveProfiles("ci")到您的配置类,它只会在配置文件ci处于活动状态时使用该类。

最后,您不需要文件中的属性spring.profiles.active=@activeProfile@application.properties因为它是从 maven 中的 surefire 插件传入的。


推荐阅读