我正在制作电报机器人,我需要.jar在云中部署它。
我正在使用intellij中的maven构建它,但是当试图在我的机器上执行时,它会抛出以下内容:
Exception in thread "main" java.lang.NoClassDefFoundError: org/telegram/telegrambots/bots/TelegramLongPollingBot<br>
正如我所理解的,这是因为maven没有将这个库打包到.jar中。
我该怎么做?
发布于 2020-08-21 04:18:05
粗略地说,你有两个选择
什么最适合你的处境是由你来决定的。你是怎么做到的:
制作一个“胖”罐子,里面有所有所需的课程。
要遵循这种方法,您可以使用Maven 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
在这种方法中,JAR只包含应用程序类。它的清单文件引用类路径,但还需要为依赖项提供JAR文件。要收集这些信息,可以使用Maven依赖插件,更确切地说是目标。您可以这样配置它:
<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文件,最后一件事是确保“瘦”JAR引用这些JAR。为此,请配置Maven Jar插件
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.mycompany.MyApplication</mainClass>
</manifest>
</archive>
</configuration>
在这种方法中,如果只更改应用程序代码的几行,那么只会替换应用程序JAR --依赖JAR将保持不变。缺点是,需要分发的不是一个文件,而是一个目录结构:应用程序JAR文件以及lib/文件夹及其内容。
https://stackoverflow.com/questions/63522466
复制