Maven Shade Plugin 默认替换构建生成的原始 jar 并创建一个以 original 为前缀的副本。
可以通过outputDirectory、outputFile和finalName配置条目来配置替换和重定位。
应用以下配置:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>default-jar</id>
<phase />
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-${project.version}-something</finalName>
<outputDirectory>../guide</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
我们是:
- 首先禁用默认jar的生成,根据您的要求和this dedicated SO Q/A指定
- 然后配置 Shade 插件以将其输出重新定位到上层
guide 文件夹(通过相对路径,@Tunaki 也建议使用更好的方法)
- 还配置
finalName 元素以禁用替换(这也会影响重定位,因为(前缀)原始jar 也将被重定位)。根据official documentation,finalName 是
阴影 artifactId 的名称。如果您想更改本机工件的名称,您可以使用<build><finalName> 设置。如果设置为不同于<build><finalName> 的值,则不会执行文件替换,即使正在使用shadedArtifactAttached。
因此,Maven 将仅在配置的位置生成阴影 jar。
另一种方法是使用outputFile 配置条目,它指定:
着色工件的输出文件的路径。设置此参数后,创建的存档既不会替换项目的主要工件,也不会附加。因此,此参数会导致参数finalName、shadedArtifactAttached、shadedClassifierName 和createDependencyReducedPom 在使用时被忽略。
因此您可以将上面的配置更改为:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>default-jar</id>
<phase />
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<outputFile>../guide/${project.artifactId}-${project.version}-shaded.jar</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
并且具有完全相同的行为。
旁注:您确实在此处更改了构建的行为。如果某人仅从模块文件夹本身构建单个模块,他/她将不会在 target 文件夹中找到预期的内容,而是在父文件夹中(有点意外)。
更新
应用上述配置并从命令行仅调用 Shade 插件
mvn shade:shade
但是,您将遇到以下问题:
[INFO] --- maven-shade-plugin:2.4.3:shade (default-cli) @ test-addjar ---
[ERROR] The project main artifact does not exist. This could have the following
[ERROR] reasons:
[ERROR] - You have invoked the goal directly from the command line. This is not
[ERROR] supported. Please add the goal to the default lifecycle via an
[ERROR] <execution> element in your POM and use "mvn package" to have it run.
[ERROR] - You have bound the goal to a lifecycle phase before "package". Please
[ERROR] remove this binding from your POM such that the goal will be run in
[ERROR] the proper phase.
[ERROR] - You removed the configuration of the maven-jar-plugin that produces the main artifact.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------