我正在制作Telegram机器人,需要一个.jar文件将其部署在云端。
我正在使用Intellij IDEA中的Maven构建它,但在尝试在我的计算机上执行时,它会报错:
Exception in thread "main" java.lang.NoClassDefFoundError: org/telegram/telegrambots/bots/TelegramLongPollingBot<br>
据我所理解,这是因为Maven没有将该库打包成.jar文件。
我该如何做呢?
我正在制作Telegram机器人,需要一个.jar文件将其部署在云端。
我正在使用Intellij IDEA中的Maven构建它,但在尝试在我的计算机上执行时,它会报错:
Exception in thread "main" java.lang.NoClassDefFoundError: org/telegram/telegrambots/bots/TelegramLongPollingBot<br>
据我所理解,这是因为Maven没有将该库打包成.jar文件。
我该如何做呢?
大致上来说,您有两个选择:
什么对于您的情况最合适,只有您自己可以决定。以下是如何操作:
要采用这种方法,您需要使用Maven Shade Plugin。在打包阶段,您将调用其shade
goal。这将把依赖项和应用程序类中的类一起复制到一个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.
https://dev59.com/qHNA5IYBdhLWcg3wWsUA
-->
<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
goal。您可以像这样进行配置:
<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>
现在您已经有了所有依赖的JAR文件在target/lib中,最后一件事是确保“瘦”JAR引用了它们。为此,请配置Maven Jar Plugin:
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.mycompany.MyApplication</mainClass>
</manifest>
</archive>
</configuration>