【发布时间】:2019-01-05 04:21:56
【问题描述】:
我一直在为我的测试框架使用 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 来运行我的项目。我做错了什么,请告诉我如何解决。
【问题讨论】:
-
如何将
@activeProfile@替换为代码中的测试?实际上对于测试,您可以使用@ActiveProfiles("ci")和@SpringBootTest -
你应该防止在你的 Spring Boot 应用程序中使用 Maven 配置文件。否则我会把它当作代码味道......
-
Maven 配置文件!= Spring 配置文件。此外,您不应该使用这样的配置文件,因为这会导致针对不同环境的不同构建。您不想这样做(因为这基本上意味着您将在未经测试的情况下进行生产)。在您的
@PropertySource中,您还试图超越 Spring Boot(它已经为您完成了所有这些,所以您不需要它)。只需在应用程序启动期间传递您希望使用的配置文件(或通过环境变量或简单地通过@ActiveProfiles在您的测试类中。 -
@m-deinum 只是为了澄清如果我在“@Configuration”类上使用“@ActiveProfiles("ci")”,那么测试将选择 application-ci.properties 文件并替换所有属性来自测试中的文件?
标签: java spring maven spring-boot testng