【问题标题】:Refer to Maven project paths from Java请参阅 Java 中的 Maven 项目路径
【发布时间】:2011-09-19 08:01:13
【问题描述】:

我需要以编程方式收集 Maven 项目中的一些路径,特别是引用项目工件。 使用

URL MyClass.class.getClassLoader().getResource(String name)

适用于相对于项目的 target/classes 文件夹的路径,但由于工件位于 target 文件夹中,因此无法引用它。像

这样的路径
System.getProperty("user.dir") + "/target"

至少不能说服我,因为 target 文件夹名称虽然是标准的,但不能安全地移植。

是否有利用相对路径的 Maven 感知库解决方案?

【问题讨论】:

  • 语境化:我正在尝试为Pax Exam 集成测试自动加载(子)项目工件。我需要从“裸”文件系统路径加载它们,因为安装在 Maven 生命周期中进一步下降。
  • target 文件夹名称的哪一部分不可移植?目录分隔符部分,还是项目的输出目录可以在项目POM中改变?
  • 我指的是项目输出目录是可定制的。

标签: java maven filepath


【解决方案1】:

MavenProperties 可以使用 maven war 插件或 maven jar 插件使用的 maven archiver 写入清单文件。

如果您有一个网络应用程序,那么您也可以将一些信息传递给 web.xml 文件。

这是我的一个项目的示例:

from pom.xml:
------------------------------------------------
<properties>
    <maven.build.timestamp.format>dd.MM.yyyy' 'HH:mm:ss</maven.build.timestamp.format>
    <build-version>${env.SVN_REVISION}</build-version>
    <build-date>${maven.build.timestamp}</build-date>
</properties>
.
.
.
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <webResources>      
                        <webResource>
                            <directory>${basedir}/src/main/webapp/WEB-INF</directory>
                            <includes>
                                <include>web.xml</include>
                            </includes>
                            <targetPath>WEB-INF</targetPath>
                            <filtering>true</filtering>
                        </webResource>
                    </webResources>

from web.xml:
------------------------------------------------
<context-param>
    <param-name>BUILD_VERSION</param-name>
    <param-value>${build-version}</param-value>
</context-param>
<context-param>
    <param-name>BUILD_DATE</param-name>
    <param-value>${build-date}</param-value>
</context-param>

【讨论】:

  • 这是一个很好的通用解决方案,因为它允许导入自定义属性。我注意到properties-maven-plugin 也支持这种特定方法。但是,由于我需要的信息已经存在于 POM 中的某个位置,因此定义其他属性对我来说似乎是多余的。
  • ${project.build.outputDirectory} 导致“目标/类”目录的路径对您没有帮助?这是我发布的第一个链接“背后”的 Maven 属性之一。
  • 是的,更准确地说,${project.build.directory} 会。那不是重点。从您提供的第二个链接中,尚不清楚我是否可以构建 additional 清单,从而不会污染最终打包的清单。我需要的信息是用于测试。
  • 我自己尝试过 - 创建或修改额外的清单,但没有成功。而且我还发现没有干净的方法可以从我的 java 代码中的 war 包的 MANIFEST.MF 文件中读取信息。这就是上述解决方案的原因。
猜你喜欢
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 2018-11-17
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多