java - 如何将选定的 Maven 配置文件传递给 Spring 配置文件?
问题描述
我有 3 个 maven 项目 A、B、C。A 是 B 的父项目,B 是 C 的父项目。所有配置文件都在pom.xml
项目 A中定义。
在项目 C 中,我试图根据所选配置文件在 spring-test-context (在src/test/resources下)中选择属性文件。对于回归测试,我们有 2 个属性文件:
- 应用程序测试本地属性
- 应用程序-test.properties
在我们的 Windows 开发系统上,选定的配置文件将是“本地的”并相应地在服务器上。When "local" profile is selected, application-test-local.properties
should be used and application-test.properties
otherwise in the test Spring context. 在项目 C中spring-test-context.xml
,我尝试了:
<beans profile="docker">
<util:properties id="metaDbProps" location="application-test-local.properties"/>
</beans>
<beans profile="default">
<util:properties id="metaDbProps" location="application-test.properties"/>
</beans>
但是,似乎应用程序无法将选定的 Maven 配置文件传递给 spring 配置文件,因为我正在尝试“mvn clean test -Pdocker”,并且它总是从“默认”配置文件中获取属性文件。
知道要修复什么以将 maven 配置文件传递给 spring 配置文件,以便它可以获取正确的属性文件吗?
为了便于理解,以下是项目 A 中配置文件的定义方式:
<profiles>
<!-- Windows development -->
<profile>
<id>docker</id>
<activation/>
<properties>
<INSTALL_MACHINE_LIST>localhost</INSTALL_MACHINE_LIST>
<COPY_MODE>local</COPY_MODE>
</properties>
</profile>
<!-- Development -->
<profile>
<id>dev</id>
<activation/>
<properties>
<INSTALL_MACHINE_LIST>dev01</INSTALL_MACHINE_LIST>
</properties>
</profile>
<!-- QA -->
<profile>
<id>qa</id>
<activation/>
<properties>
<INSTALL_MACHINE_LIST>dqa01</INSTALL_MACHINE_LIST>
</properties>
</profile>
<!-- Production -->
<profile>
<id>prod</id>
<activation/>
<properties>
<INSTALL_MACHINE_LIST>prod01</INSTALL_MACHINE_LIST>
</properties>
</profile>
</profiles>
解决方案
默认情况下,Maven 测试使用Maven Surefire Plugin运行。您可以将 Spring 配置文件声明为 Maven 配置文件中的属性:
<profile>
<id>docker</id>
<properties>
<spring.profiles.active>docker</spring.profiles.active>
</properties>
</profile>
然后使用<argLine>
配置将其传递给 Surefire:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dspring.profiles.active=@{spring.profiles.active} @{argLine}</argLine>
</configuration>
</plugin>
</plugins>
</build>
请注意@{...}
语法:
由于 2.17 版使用 argLine 的替代语法,@{...} 允许在执行插件时延迟替换属性,因此已被其他插件修改的属性将被正确拾取
推荐阅读
- php - 如何在PHP中合并两个不重复的多数组
- javascript - 如何正确转义此正则表达式构造中的字符
- css - Flex 半自举
- python - 最长和最短序列,Python
- retinanet - 训练 fizyr/keras-retinanet 的数据集中图像的最大标签数?
- java - Spring Boot 中的 Kafka 生产者错误处理
- matlab - MATLAB 的 mxGetFieldByNumber 和 mxGetFieldNameByNumber 返回不一致的结果
- list - 为什么在使用 append 功能时,列表末尾需要一个 0 ?我可以用另一个数字替换 0 吗?
- python - when is a local namespace to be destructed in python?
- discord - Discord.py on_message 客户端甚至干扰客户端命令