我一直在使用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
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来运行我的项目。我正在做一些不正确的事情,让我知道如何解决它。
首先,maven概要文件与spring概要文件不同。在提供的代码片段中,您正在设置maven概要文件,而不是spring概要文件。
要在测试阶段传递特定的spring配置文件,可以使用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将首先加载application.properties
,然后在其上应用application-ci.properties
@PropertySource("classpath:application-${spring.profiles.active}.properties")
不需要。
如果您有一个特定于活动配置文件的配置类,那么您可以将@ActiveProfiles("ci")
添加到您的配置类中,并且它只会在配置文件ci
处于活动状态时使用该类。
最后,您不需要application.properties
文件中的属性spring.profiles.active=@activeProfile@
,因为它是从maven中的surefire插件传入的。