Maven2属性,指示父目录

问题描述 投票:95回答:18

我有一个多模块项目,像这样:

main-project/
    module1/
    module2/
        sub-module1/
        sub-module2/
        sub-module3/
        ...
    module3/
    module4/
    ...

我需要在Maven2中定义一组属性(取决于我想要释放项目的环境)。我不会使用<properties>,因为有很多属性......因此,我使用Properties Maven2 plugin

属性文件位于main-project/目录中。如何在主pom.xml中设置正确的目录,以便为任何子项指定在哪里找到属性文件?

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0-alpha-1</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>read-project-properties</goal>
            </goals>
            <configuration>
                <files>
                    <file>???/env_${env}.properties</file>
                </files>
            </configuration>
        </execution>
    </executions>
</plugin>

如果我只设置<file>env_${env}.properties</file>,那么当Maven2编译第一个模块时,它将找不到main-project/env_dev.properties文件。如果我设置<file>../env_${env}.properties</file>,那么将在父级别或任何子模块级别引发错误...

maven-2 properties
18个回答
151
投票

尝试在每个pom中设置属性以查找主项目目录。

在父母:

<properties>
    <main.basedir>${project.basedir}</main.basedir>
</properties>

在孩子们:

<properties>
    <main.basedir>${project.parent.basedir}</main.basedir>
</properties>

在孙子孙女:

<properties>
    <main.basedir>${project.parent.parent.basedir}</main.basedir>
</properties>

3
投票

您在项目C中,项目C是B的子模块,B是A的子模块。您尝试从项目C到达模块D的src/test/config/etc目录.D也是A的子模块。以下表达式使得获取URI路径成为可能:

-Dparameter=file:/${basedir}/../../D/src/test/config/etc

2
投票
<plugins>
  <plugin>
    <groupId>org.codehaus.groovy.maven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.0</version>
    <executions>
      <execution>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
        <configuration>
          <source>
            import java.io.File
            project.properties.parentdir = "${pom.basedir}"
            while (new File(new File(project.properties.parentdir).parent, 'pom.xml').exists()) {
                project.properties.parentdir = new File(project.properties.parentdir).parent
            }
          </source>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0-alpha-2</version>
    <executions>
      <execution>
        <phase>initialize</phase>
        <goals>
          <goal>read-project-properties</goal>
        </goals>
        <configuration>
          <files>
            <file>${parentdir}/build.properties</file>
          </files>
        </configuration>
      </execution>
    </executions>
  </plugin>
  ...

1
投票

answer to another question中,我展示了如何扩展maven-properties-plugin以使用Maven依赖项中定义的外部属性描述符。

您可以将该想法扩展为具有多个描述符jar,每个描述符jar都具有作为artifactId一部分的环境名称,包含$ {env} .properties。然后,您可以使用该属性选择适当的jar和属性文件,例如:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>properties-ext-maven-plugin</artifactId>
  <version>0.0.1</version>
  <executions>
    <execution>
      <id>read-properties</id>
      <phase>initialize</phase>
      <goals>
        <goal>read-project-properties</goal>
      </goals>
    </execution>
  </executions>                              
  <configuration>
    <filePaths>
      <!--assume the descriptor project has a file in the root of the jar -->
      <filePath>${env}.properties</filePath>
    </filePaths>
  </configuration> 
  <dependencies>
    <!-- reference the properties jar for the particular environment-->
    <dependency>
      <groupId>some.descriptor.group</groupId>
      <artifactId>env-${env}-descriptor</artifactId>
      <version>0.0.1</version>
    </dependency>
  </dependencies>
</plugin>

1
投票

我只是从上面改进groovy脚本,在root父属性文件中写入属性:

import java.io.*;
String p = project.properties['env-properties-file']
File f = new File(p)
if (f.exists()) {
try{
FileWriter fstream = new FileWriter(f.getAbsolutePath())
BufferedWriter out = new BufferedWriter(fstream)
String propToSet = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator))
if (File.separator != "/") {
propToSet = propToSet.replace(File.separator,File.separator+File.separator+File.separator)
}
out.write("jacoco.agent = " + propToSet + "/lib/jacocoagent.jar")
out.close()
}catch (Exception e){
}
}
String ret = "../"
while (!f.exists()) {
f = new File(ret + p)
ret+= "../"
}
project.properties['env-properties-file-by-groovy'] = f.getAbsolutePath()

1
投票

我使用$ {basedir} .. \ src \访问上面的目录


0
投票

你尝试过../../env_${env}.properties吗?

通常,当module2与子模块位于同一级别时,我们执行以下操作

<modules>
    <module>../sub-module1</module>
    <module>../sub-module2</module>
    <module>../sub-module3</module>
</modules>

我认为../ ..会让你跳两个级别。如果没有,您可能想联系插件作者,看看这是否是一个已知问题。


0
投票

我认为如果你使用findbugs插件和多模块的例子中使用的扩展模式,你可以设置与绝对路径相关的全局属性。它使用顶部

example for multi module

顶级pom有一个不相关的build-config项目和一个app-parent,用于多模块项目的模块。 app-parent使用扩展将自身链接到build-config项目并从中获取资源。这用于将常见配置文件传送到模块。它也可能是物业的管道。您可以将top dir写入build-config使用的属性文件。 (看起来太复杂了)

问题是必须在多模块项目中添加新的顶级才能使其工作。我试图与一个真正无关的build-config项目迈出一步,但它很笨拙而且似乎很脆弱。


0
投票

这扩展了romaintaz的答案,这很棒,因为它解决了问题并且还清楚地指出了maven缺少的功能。我选择了该插件的更高版本,并添加了项目可能超过3级深度的情况。

<pluginManagement>
  <plugins>
    ..
    <plugin>
      <groupId>org.codehaus.gmaven</groupId>
      <artifactId>groovy-maven-plugin</artifactId>
      <version>2.0</version>
    </plugin>
    ..
  </plugins>
</pluginManagement>

我选择不使用属性来定义文件名。请注意,如果找不到build.properties,这将永远旋转。我添加了一个.git dir检测,但是不想让响应复杂化,所以这里没有显示。

  <plugin>
      <groupId>org.codehaus.gmaven</groupId>
      <artifactId>groovy-maven-plugin</artifactId>
      <executions>
          <execution>
              <phase>validate</phase>
              <goals>
                  <goal>execute</goal>
              </goals>
              <configuration>
                 <source>
                    import java.io.File;
                    String p = "build.properties";
                    while(true) {
                      File f = new File(p); 
                      if(f.exists()) {
                        project.properties['project-properties-file'] = f.getAbsolutePath();
                        break;
                      }
                      else {
                        p = "../${p}";
                      }
                    }
                </source>
              </configuration>
          </execution>
      </executions>
  </plugin>

0
投票

我需要为多模块项目的主项目中的本地存储库解决类似的问题。基本上真正的路径是${basedir} / lib。最后我在我的parent.pom中解决了这个问题:

<repository>
    <id>local-maven-repo</id>
    <url>file:///${basedir}/${project.parent.relativePath}/lib</url>
</repository>

basedir总是显示当前的本地模块,没有办法获得“主”项目的路径(Maven的耻辱)。我的一些子模块是一个dir更深,一些是更深的两个dirs,但它们都是定义repo URL的父项的直接子模块。

所以这并不能解决一般问题。您可以将它与Clay的接受答案结合起来并定义其他一些属性 - 工作正常,只有在parent.pom的值不够好的情况下才需要重新定义。或者您可以重新配置插件 - 您只在POM工件(其他子模块的父节点)中执行此操作。如果您需要在更多地方使用它,那么提取到属性中的值可能会更好,尤其是当插件配置中没有任何内容发生更改时

在这里使用basedir是必不可少的部分,因为URL file://${project.parent.relativePath}/lib不想做这个技巧(我删除了一个斜杠使其相对)。使用给我良好绝对路径然后从中获取相关性的属性是必要的。

当路径不是URL / URI时,丢弃basedir可能不是一个问题。


14
投票

我找到了解决问题的解决方案:我使用Groovy Maven插件搜索属性文件。

由于我的属性文件必须在当前目录中,在../或.. / ..中,我编写了一个小的Groovy代码来检查这三个文件夹。

这是我的pom.xml的摘录:

<!-- Use Groovy to search the location of the properties file. -->
<plugin>
    <groupId>org.codehaus.groovy.maven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.0-rc-5</version>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
                    import java.io.File;
                    String p = project.properties['env-properties-file'];
                    File f = new File(p); 
                    if (!f.exists()) {
                        f = new File("../" + p);
                        if (!f.exists()) {
                            f = new File("../../" + p);
                        }
                    }
                    project.properties['env-properties-file-by-groovy'] = f.getAbsolutePath();
            </source>
            </configuration>
        </execution>
    </executions>
</plugin>
<!-- Now, I can load the properties file using the new 'env-properties-file-by-groovy' property. -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0-alpha-1</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>read-project-properties</goal>
            </goals>
            <configuration>
                <files>
                    <file>${env-properties-file-by-groovy}</file>
                </files>
            </configuration>
        </execution>
    </executions>
</plugin>

这很有用,但我真的不喜欢它。

所以,如果你有更好的解决方案,请不要犹豫发布!


14
投票

使用directory-maven-plugin with directory-of goal

与其他建议不同:

  • 此解决方案适用于多模块项目。
  • 无论您是构建整个项目还是子模块,它都有效。
  • 无论您是从根文件夹还是子模块运行maven,它都有效。
  • 不需要在每个子模块中设置相对路径属性!

该插件允许您将所选属性设置为任何项目模块的绝对路径。在我的情况下,我将它设置为根模块...在我的项目根pom:

<plugin>
    <groupId>org.commonjava.maven.plugins</groupId>
    <artifactId>directory-maven-plugin</artifactId>
    <version>0.1</version>
    <executions>
        <execution>
            <id>directories</id>
            <goals>
                <goal>directory-of</goal>
            </goals>
            <phase>initialize</phase>
            <configuration>
                <property>myproject.basedir</property>
                <project>
                    <groupId>com.my.domain</groupId>
                    <artifactId>my-root-artifact</artifactId>
                </project>
            </configuration>
        </execution>
    </executions>
</plugin>

从那时起,任何子模块pom中的$ {myproject.basedir}始终具有项目根模块的路径。当然,您可以将属性设置为任何模块,而不仅仅是根...


11
投票

所以我看到的问题是你无法获得maven中父目录的绝对路径。

<rant> I've heard this talked about as an anti-pattern,但是对于每一个反模式都有真实合法的用例,而且我厌倦了maven告诉我我只能遵循他们的模式。

所以我发现的工作是使用antrun。在子pom.xml中尝试这个:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <id>getMainBaseDir</id>
            <phase>validate</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <exportAntProperties>true</exportAntProperties>
                <target>
                    <!--Adjust the location below to your directory structure -->
                    <property name="main.basedir" location="./.." />
                    <echo message="main.basedir=${main.basedir}"/>
                </target>
            </configuration>
        </execution>
    </executions>
</plugin>

如果你运行mvn verify你应该看到这样的东西:

main:
     [echo] main.basedir=C:\src\parent.project.dir.name

然后你可以在任何其他插件中使用${main.basedir}等。花了一些时间来弄明白这一点,所以希望它可以帮助别人。


7
投票

至少在当前的maven版本(3.6.0)中,您可以使用${maven.multiModuleProjectDirectory}


6
投票

以下小配置文件对我有用。我需要CheckStyle这样的配置,我把它放在项目根目录的config目录中,所以我可以从主模块和子模块运行它。

<profile>
    <id>root-dir</id>
    <activation>
        <file>
            <exists>${project.basedir}/../../config/checkstyle.xml</exists>
        </file>
    </activation>
    <properties>
        <project.config.path>${project.basedir}/../config</project.config.path>
    </properties>
</profile>

它不适用于嵌套模块,但我相信它可以使用不同exists的几个配置文件进行修改。 (我不知道为什么在验证标签中应该有“../ ..”而在overriden属性本身中只有“..”,但它只能以这种方式工作。)


6
投票

在我的情况下它的工作原理如下:

...
<properties>
  <main_dir>${project.parent.relativePath}/..</main_dir>
</properties>
...

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                 <file>${main_dir}/maven_custom.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
</plugin>

6
投票

另一种选择:

在父pom中,使用:

<properties>
   <rootDir>${session.executionRootDirectory}</rootDir>
<properties>

在儿童poms中,您可以引用此变量。

主要警告:它强制您始终从主父pom目录执行命令。然后,如果您只想为某些特定模块运行命令(例如测试),请使用以下语法:

mvn test --projects

然后,用于参数化“path_to_test_data”变量的surefire配置可以是:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${surefire.plugin.version}</version>
    <configuration>
        <systemPropertyVariables>
            <path_to_test_data>${rootDir}/../testdata</path_to_test_data>
        </systemPropertyVariables>
    </configuration>
</plugin>

3
投票

我找到了解决这个问题的解决方案:使用$ {parent.relativePath}

<parent>
    <artifactId>xxx</artifactId>
    <groupId>xxx</groupId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
</parent>
<build>
    <filters>
        <filter>${parent.relativePath}/src/main/filters/filter-${env}.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
© www.soinside.com 2019 - 2024. All rights reserved.