maven - “无法找到或加载主类”从执行“mvn install”中生成的 JAR
问题描述
我正在尝试使用 Maven 从 Groovy 代码生成 JAR 文件。它运行良好,类在 jar 文件中,但它给了我错误Error: Could not find or load main class me.strafe.hello.Main
。
pom.xml
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<configuration>
<tasks>
<mkdir dir="${basedir}/src/main/groovy"/>
<taskdef name="groovyc"
classname="org.codehaus.groovy.ant.Groovyc">
<classpath refid="maven.compile.classpath"/>
</taskdef>
<mkdir dir="${project.build.outputDirectory}"/>
<groovyc destdir="${project.build.outputDirectory}"
srcdir="${basedir}/src/main/groovy/"
listfiles="true">
<classpath refid="maven.compile.classpath"/>
</groovyc>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>me.strafe.hello.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
我从 Groovy 文档中获取了这个。
树:
├── pom.xml
├── src
│ └── main
│ └── groovy
│ └── Main.groovy
Main.groovy:
package me.strafe.hello
class Main {
static void main(String[] args) {
println "Hello, World!"
}
}
我也尝试过使用 gradle,但我对它不太熟悉,因为我以前使用过 maven。
解决方案
如果你像这样运行程序,它将工作:
java -cp my.jar me.strafe.hello.Main
确保将任何其他 jars(如 groovy jars)添加到类路径中,如下所示(文件分隔符:
在 Linux 上,;
在 Windows 上):
java -cp libs/groovy-all.jar:my.jar me.strafe.hello.Main
您还可以将 POM 配置为生成一个“胖 jar”,其中包含单个 jar 中的依赖项,以使其更容易。
如果你真的希望你的 jar 是可运行的,那么你应该像上面那样做,但还要将Main-Class
声明添加到 jar 的清单中,这样你就不需要在命令行中指定主类,如上所示。
一旦你做了这两件事(fat jar 和在 Manifest 中声明的 Main-Class),这个命令也将起作用:
java -jar my.jar
推荐阅读
- c++ - 使类在使用时调用正确的构造函数
- visual-studio-2017 - Review Assistant 中的 Initial Review 和 Regular Review 有什么区别?
- amazon-web-services - 如何使用 Amplify 控制台作为反向代理
- php - 无法在视图页面中调用下拉菜单
- angular - owl-carousel-o 响应选项不起作用 Angular 7.2.9
- jquery - 如何使用 jQuery Validate 验证只有单个表单的多步表单
- android - 我为什么要利用这个设计?
- html - 对象拟合 - 未知属性
- java - Spring AOP java.lang.IllegalArgumentException:::0 处的错误在切入点中正式未绑定
- python - 测试偶数字母,为什么我的函数内外的索引不同?