有没有办法创建一个包含当前项目中的类的 jar 和一个仅包含外部库的阴影 jar?
我正在通过网络移动最终的 Artifact ,如果在没有外部依赖项发生变化的情况下我只需要复制“slim”jar,那就太好了。
最佳答案
默认情况下,Maven 已经通过 Maven Jar Plugin 生成您提到的 slim jar(即提供项目中的类和资源的 jar)。默认情况下 package阶段(例如,调用 mvn clean package
或 mvn clean install
,它级联也会调用 package
阶段)。
如果您想生成一个仅提供外部库的额外 jar,无论出于何种原因,您确实可以使用 Maven Shade Plugin 。但默认情况下,它还会添加您的项目类和资源。
应用下面的配置,您将指示插件仅打包外部库并跳过您的项目类和资源:
<build>
<plugins>
<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>
<artifactSet>
<excludes>
<exclude>${project.groupId}:${project.artifactId}:*</exclude>
</excludes>
</artifactSet>
<finalName>${project.artifactId}-${project.version}-only-dependencies</finalName>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
请注意 exclude
元素,它会有效地跳过您的项目内容。
此外,需要配置finalName
元素,以避免插件的默认机制将原来的默认jar(上面提到的)替换为fat/uber jar(jar +依赖项) ).
根据official documentation :
The name of the shaded artifactId. If you like to change the name of the native artifact, you may use the setting. If this is set to something different than , no file replacement will be performed
运行mvn clean package
,然后您将拥有默认的 jar 文件和一个仅包含外部依赖项的附加 jar 文件,并以 only-dependencies
后缀结尾(在 jar 之前)扩展名)。
此外,您可以考虑将上面的整个配置包装在 profile 中。 ,以避免将此行为作为默认构建的一部分(推荐)。
只需将上面的配置移动到包装配置文件中,如下所示:
<profiles>
<profile>
<id>assemble-external-jars</id>
<build>
....
</build>
</profile>
</profiles>
然后通过以下方式运行它(需要时):
mvn clean package -Passemble-external-jars
关于maven - 仅使用外部库的 Shaded jar - Maven Shade 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35204657/