我知道 Maven 属性可以在不同位置定义:
-
~/.m2/settings.xml
在本地计算机上 -
<properties>
在项目父 POM 中 -
<properties>
在项目子模块POM中 -
<properties>
在项目父 POM 的 Maven 配置文件中 -
<properties>
在项目子模块 POM 的 Maven 配置文件中 -
-D
直接在命令行上
但是并不清楚属性的加载顺序。有人能解释一下它的顺序吗?
最佳答案
根据我的测试,属性的优先级似乎如下,其中 1. 优先于 2.; 2. 优先于 3. 等等。
-
-D
通过命令行获取属性 -
<properties>
在<profile>
在settings.xml
-
<properties>
在<profile>
在子 pom 中 -
<properties>
直接在子pom中 -
<properties>
在<profile>
在父pom中 -
<properties>
直接在父pom中
一般来说:
- 命令行优先
- 设置先于子级,后于父级
- 在直接定义的属性之前进行配置
我使用以下设置对其进行了测试。
设置.xml
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<custom.prop>settings</custom.prop>
</properties>
</profile>
</profiles>
</settings>
父pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<custom.prop>parent</custom.prop>
</properties>
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<custom.prop>parent-profile</custom.prop>
</properties>
</profile>
</profiles>
</project>
子pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test-child</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>test</groupId>
<artifactId>test-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>parent/pom.xml</relativePath>
</parent>
<properties>
<custom.prop>child</custom.prop>
</properties>
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<custom.prop>child-profile</custom.prop>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<echo message="${custom.prop}" />
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
像这样运行它并删除 echo
属性ed,只要还有属性就重复。
关于java - Maven 属性加载顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49598655/