我有一个简单的 Maven 项目,只有一个依赖项。我可以安装它并通过 Exec Maven Plugin 命令行运行它:
mvn exec:java -D"exec.mainClass"="com.MyClass"
打包后maven会在我的目录下生成一个.jar文件。在Maven JAR Plugin的帮助下我做了它的 list 来了解我的 main
方法类。它看起来像:
...
Created-By: Apache Maven 3.3.1
Build-Jdk: 1.8.0_66
Main-Class: com.MyClass
现在我想使用 java
命令像常规 java 可执行文件一样运行这个 .jar 文件,但在执行以下操作之后:
java -jar myFile.jar
它给出了一个关于我唯一的依赖项的错误java.lang.NoClassDefFoundError
。
如何让 maven 将所有依赖项添加到我的可执行 jar 文件中?
最佳答案
实现此目的的一种方法是使用 Apache Maven Shade Plugin :
This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies.
这个插件对于具有许多依赖项的大型项目有一些优势。对此进行了解释:Difference between maven plugins ( assembly-plugins , jar-plugins , shaded-plugins)
在我的项目中,我使用以下配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.xxx.tools.imagedump.ImageDumpLauncher</mainClass>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
关于java - Maven exec 有效,但 java -jar 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382751/