大家好 stackoverflow,在我的工作项目中我有 5 个依赖项。 我正在开发一个不包含任何主要方法的项目。
我想做的是在最终的 jar 中包含 5 个依赖项中的 2 个(HikariCP 和 slf4j),但我不知道如何做到这一点,它总是添加所有依赖项。
编辑:我正在使用 eclipse
最佳答案
使用 Maven
您可以使用maven-shade-plugin
生成fat-jar(或uber-jar)。它将把所有依赖项打包到 jar 中:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<finalName>YOUR_JAR_FINAL_NAME</finalName>
</configuration>
</plugin>
</plugins>
</build>
与 maven-shade-plugin
相关的文档 can be found in here
更新:由于您只想在其中包含一些依赖项,因此您可以检查 Selecting contents for Uber JAR部分:
您可以使用 include 或 exclude 标签来选择将向 jar 提供哪些内容,您可以从下面的文档中找到一些示例:
排除
<configuration> <artifactSet> <excludes> <exclude>classworlds:classworlds</exclude> <exclude>junit:junit</exclude> <exclude>jmock:*</exclude> <exclude>*:xml-apis</exclude> <exclude>org.apache.maven:lib:tests</exclude> <exclude>log4j:log4j:jar:</exclude> </excludes> </artifactSet> </configuration>
包含和排除
<configuration> <filters> <filter> <artifact>junit:junit</artifact> <includes> <include>junit/framework/**</include> <include>org/junit/**</include> </includes> <excludes> <exclude>org/junit/experimental/**</exclude> <exclude>org/junit/runners/**</exclude> </excludes> </filter> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration>
更新2:对于可运行的jar文件,您可以按照 this section of the documentation与可执行 jar
相关在 Eclipse 中
您可以使用“将所需的库打包到生成的 JAR 中”选项,其缺点是您无法真正选择要包含哪些依赖项,因为它正在评估所有您的项目所需的库。
我相信如果你真的想删除一些东西,你需要使用Maven来打包,或者从生成的jar中手动删除你不喜欢的依赖项,用自己的双手生成一个自定义jar:
关于java - 在我编译的 jar 中包含一些依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54095401/