我有一个 Java 项目,它将一些资源文件打包到 Artifact jar 中。这些文件来自一个 zip,该 zip 被版本化并存储在与项目的 Artifact 相同的 Artifact 中。该 zip 被引用为具有版本范围的依赖项。
zip 被列为依赖项:
<dependency>
<groupId>com.example</groupId>
<artifactId>resource-files</artifactId>
<version>[1.68.0,1.68.1)</version>
<type>zip</type>
<scope>provided</scope>
</dependency>
然后用依赖插件解压:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>generate-sources</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
<configuration>
<includes>**/*.bin</includes>
<outputDirectory>${basedir}/import</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
然后作为资源添加到 jar 中:
<resource>
<directory>${project.basedir}/import/resource-files-${version????}</directory>
<includes>
<include>*</include>
</includes>
<targetPath>bins</targetPath>
</resource>
如何确定 Artifact zip 的确切版本?如果可能的话,我想跳过修改 pom(就像 versions:resolve-ranges 那样)。
最佳答案
这很有趣...
我找到了两种获取解析版本的方法:使用特定的插件,或者使用一个小的 groovy 脚本从 maven 查询它。
插件
有一个 dependencyversion-maven-plugin
:
<plugin>
<groupId>io.reformanda.semper</groupId>
<artifactId>dependencyversion-maven-plugin</artifactId>
<version>1.0.1</version>
<executions>
<execution>
<id>set-all</id>
<goals>
<goal>set-version</goal>
</goals>
</execution>
</executions>
</plugin>
它以 groupId:artifactId:type[:classifier].version
的格式为每个依赖项创建新属性具有已解决的版本值。更多详情 here .
常规
同样的结果可以用一个小的 groovy 脚本实现:
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
for (art in project.getArtifacts())
project.properties['resolvedVersion.' + art.getArtifactId()] = art.getVersion()
</source>
</configuration>
</execution>
</executions>
</plugin>
由于 groovy-maven-plugin 很好地公开了 maven 内部结构,因此可以实现各种技巧。
快到了...
上述两种解决方案都使用已解析版本定义了一组新属性,但不幸的是,它们在 <build><resources>
中不可用。堵塞。我还没有找到关于此的文档,但似乎此 block 中的属性在生命周期开始之前已被替换,并且新定义的属性此时根本不存在。
我发现的唯一解决方法是显式调用 copy-resources
目标 resources
插件:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-resources</id>
<goals>
<goal>copy-resources</goal>
</goals>
<phase>process-resources</phase>
<configuration>
<outputDirectory>${project.build.outputDirectory}</outputDirectory>
<resources>
<resource>
<filtering>false</filtering>
<directory>${basedir}/import/resource-files-${resolvedVersion.resource-files}/lib</directory>
<includes>
<include>*</include>
</includes>
<targetPath>bins</targetPath>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
有了这个 block (并替换了 <build><resources>
),所有资源都正确复制了,并且不需要硬编码任何东西。
虽然这可能不是最优雅的方式...
关于Maven:将版本范围解析为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55452645/