java - 使用 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 来运行我的项目。我在做一些不正确的事情,让我知道如何解决它。
解决方案
首先,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 插件传入的。
推荐阅读
- javascript - 使用状态未更新
- php - 从 datalist 下拉列表中选择多个数据
- node.js - 从 Flutter 录制音频数据(16000Hz PCM 数据),捕获音频并将其发送到后端(Node.js)
- sql-server - 如何在基于状态的连续数据库部署中实现参考数据
- javascript - 为什么当我添加整数时我的过滤器不起作用?
- python - python 使用 *args 和 **kwargs 以及其他仅位置和关键字参数解包 arg 列表
- ansible - 来自 ansible 网络接口的订单列表
- python-3.x - 比较python中的嵌套列表并输出列表中缺少的项目
- java - KeyEvent.ACTION_UP 仅在我使用计算机键盘时有效,但在 android 虚拟键盘中无效
- javascript - FORMIO - 使用默认值共同填充表单(未记录?或不支持?)