仅使用外部库的阴影 jar

Shaded jar only with external libraries

我想问一下有关 Maven Shade 插件的问题。有没有办法从当前项目创建一个带有 类 的 jar 和一个仅包含外部库的阴影 jar?

我正在通过网络移动最终工件,如果我只需要复制 "slim" jar 如果没有外部依赖项发生变化,那就太好了。

默认情况下,Maven 已经通过 Maven Jar Plugin and by default during the 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 文件和一个仅包含外部依赖项并以 only-dependencies 后缀(在 jar 扩展名之前)结尾的附加 jar 文件。


此外,您可以考虑将上面的整个配置包装在 profile 中,以避免将此行为作为默认构建的一部分(推荐)。

只需将上面的配置移动到包装配置文件中,如下所示:

<profiles>
    <profile>
        <id>assemble-external-jars</id>
        <build>
           ....
        </build>
    </profile>
</profiles>

然后 运行 它(需要时)通过:

mvn clean package -Passemble-external-jars