使用application.properties文件激活配置文件以进行弹簧启动测试

时间:2018-07-28 04:53:44

标签: java spring maven spring-boot testng

我一直在使用Spring Boot和TestNG作为我的测试框架,到目前为止,我的测试已配置为仅使用一个默认的application.properties文件,该文件位于src / main / resource下。现在,我想为不同的环境配置它们-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运行我的项目。我做错了什么,让我知道如何解决。

1 个答案:

答案 0 :(得分:0)

首先,Maven轮廓与弹簧轮廓不同。在提供的代码段中,您正在设置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 profile自动加载属性源。在您的示例中,spring将首先加载application.properties,然后将application-ci.properties应用于其顶部。结果

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

不需要。

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

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