[英]java-maven-idea: including external library in jar
我正在制作电报机器人,我需要.jar 将其部署在云中。
我在 intellij idea 中使用 maven 构建它,但是当尝试在我的机器上执行时,它会抛出这个:
Exception in thread "main" java.lang.NoClassDefFoundError: org/telegram/telegrambots/bots/TelegramLongPollingBot<br>
据我了解,这是因为 maven 没有将此库打包到.jar 中。
我怎样才能做到这一点?
粗略地说,你有两个选择
什么最适合您的情况,只有您可以决定。 这是你如何做到的:
要遵循这种方法,您可以使用Maven 阴影插件。 在 package 阶段,您将调用其shade
目标。 这会将依赖项中的类以及应用程序类一起复制到一个 JAR 文件中。 它在 POM 中可能如下所示:
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>my-packaged-application</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.mycompany.MyApplication</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<!--
Shading signed JARs will fail without this.
http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar
-->
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
这种方法的优点是您的应用程序被打包为一个文件。 缺点是比较大。 即使您只为新版本更改几行代码,整个文件也会有所不同。
在这种方法中,JAR 仅包含您的应用程序类。 它的清单文件引用了类路径,但您还需要为依赖项提供 JAR 文件。 要收集这些,请使用Maven 依赖插件,更具体地说是copy-dependencies
目标。 你像这样配置它:
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
现在您在target/lib中拥有所有依赖 JAR 文件,最后一件事是确保“瘦” JAR 引用这些文件。 为此,请配置Maven Jar 插件:
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.mycompany.MyApplication</mainClass>
</manifest>
</archive>
</configuration>
在这种方法中,如果您只更改应用程序代码的几行,则只会替换应用程序 JAR - 依赖项 JARs 保持不变。 不利的一面是,它要求您分发的不是一个文件而是一个目录结构:应用程序 JAR 文件以及lib/文件夹及其内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.