Maven+Dropwizard项目执行java -jar时找不到主类问题求助
解决Dropwizard Maven项目Jar包无法找到主类的问题
以下是几种可能的原因及对应的解决办法:
1. 依赖未被打包进Jar包
你用java -cp仅指定了自身项目的Jar,但Dropwizard核心类(比如io.dropwizard.Application)并不在这个Jar中,主类加载时找不到父类,最终触发“找不到主类”的错误。
解决方法:使用Maven Shade插件或Dropwizard官方Maven插件打包包含所有依赖的可执行Jar:
- 若使用Dropwizard插件,在
pom.xml中添加:
<build> <plugins> <plugin> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-maven-plugin</artifactId> <version>${dropwizard.version}</version> <executions> <execution> <goals> <goal>package</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
执行mvn clean package后,生成的Jar会包含所有依赖。
- 若使用Shade插件,在
pom.xml中添加:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.dexcane.server.MyApplication</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build>
2. MANIFEST.MF配置错误
用java -jar运行时,Jar包的META-INF/MANIFEST.MF必须正确指定Main-Class属性。你可以用以下命令检查:
unzip -p target/dexcane-backend-1.0-SNAPSHOT.jar META-INF/MANIFEST.MF
如果没有Main-Class: com.dexcane.server.MyApplication这一行,说明打包时未配置主类。除了上述插件配置,也可直接在Maven Jar插件中指定:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.3.0</version> <configuration> <archive> <manifest> <mainClass>com.dexcane.server.MyApplication</mainClass> </manifest> </archive> </configuration> </plugin>
3. 类文件损坏或包名不一致
虽然jar tf显示类文件存在,但可进一步验证类的有效性:
javap -cp target/dexcane-backend-1.0-SNAPSHOT.jar com.dexcane.server.MyApplication
如果命令报错,说明类文件损坏。另外要确认主类的全限定名与命令中的拼写完全一致(Java类名大小写敏感)。
4. 环境类路径冲突
检查Java环境是否存在类路径干扰,比如系统CLASSPATH环境变量可能包含冲突Jar包。可清空CLASSPATH后再尝试:
unset CLASSPATH java -cp target/dexcane-backend-1.0-SNAPSHOT.jar:./lib/* com.dexcane.server.MyApplication
注:Windows系统路径分隔符用;替代:
内容的提问来源于stack exchange,提问作者Victor Cui
相关产品推荐
相关产品推荐

