You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Maven父POM中通过${}变量访问其自身所在目录

解决方案

Maven 3.3.1及以上版本提供了内置变量${maven.multiModuleProjectDirectory},会自动指向多模块项目的根目录(即父POM所在的根目录),完全符合你的需求。

方案1:使用内置变量(推荐)

直接修改父POM中插件的configFile配置即可:

<plugin>
    <groupId>net.revelc.code.formatter</groupId>
    <artifactId>formatter-maven-plugin</artifactId>
    <version>2.16.0</version>
    <configuration>
        <!-- 替换为多模块根目录变量 -->
        <configFile>${maven.multiModuleProjectDirectory}/java-formatter-configuration.xml</configFile>
        <overrideConfigCompilerVersion>true</overrideConfigCompilerVersion>
        <compilerSource>11</compilerSource>
        <compilerCompliance>11</compilerCompliance>
        <compilerTargetPlatform>11</compilerTargetPlatform>
        <lineEnding>CRLF</lineEnding>
        <encoding>UTF-8</encoding>
    </configuration>        
    <executions>
        <execution>
            <goals>
                <goal>format</goal>
            </goals>
        </execution>
    </executions>
</plugin>

修改后仅需在父项目根目录保留一份java-formatter-configuration.xml,所有子项目构建时会自动从父目录读取配置,无需重复复制文件。

方案2:兼容低版本Maven

如果你的Maven版本低于3.3.1,且所有子项目都是父项目的直接子模块,可以直接使用${project.parent.basedir}指向父项目目录:

<configFile>${project.parent.basedir}/java-formatter-configuration.xml</configFile>

如果存在多层嵌套的子模块,对应拼接parent层级即可,比如孙子模块使用${project.parent.parent.basedir}。

验证方式

你可以执行以下命令打印变量值,确认路径是否正确:

mvn help:evaluate -Dexpression=maven.multiModuleProjectDirectory -q -DforceStdout

内容的提问来源于stack exchange,提问作者Dimitrios Efthymiou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:57:05