You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Maven项目运行K8s Java示例遇NoClassDefFoundError问题求助

Hey there! That NoClassDefFoundError you're seeing is super common when running a Maven-built Java app directly with java -cp—here's why and how to fix it:

Why This Happens

When you run mvn clean package, Maven builds a JAR that only contains your project's own code—none of the external dependencies (like the Kubernetes client Java library) are included. So when you try to execute the JAR with java -cp, the JVM can't locate the ApiException class from the k8s client dependency, hence the error.

Fix 1: Use Maven Exec Plugin (Simplest for Testing)

Skip building a standalone JAR entirely and use Maven's Exec plugin to run your main class. This plugin automatically pulls in all required dependencies into the classpath for you.

Run this command from your project root:

mvn exec:java -Dexec.mainClass="com.mycompany.app.App"

Fix 2: Build a Fat/Shadow JAR (For Standalone Execution)

If you need a self-contained JAR that includes all dependencies (great for deploying or sharing), use the Maven Shade plugin to build a "fat JAR".

  1. Add the Shade plugin to your pom.xml inside the <build><plugins> section:
<build>
    <plugins>
        <!-- Existing plugins (if any) go here -->
        <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.mycompany.app.App</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
  1. Rebuild your project:
mvn clean package
  1. Run the fat JAR (it will be the larger JAR file in your target directory):
java -jar target/my-app-1.0-SNAPSHOT.jar

You could list every dependency JAR from your local Maven repository in the java -cp command, but this is tedious and error-prone. For example:

java -cp "target/my-app-1.0-SNAPSHOT.jar:$HOME/.m2/repository/io/kubernetes/client-java/10.0.0/client-java-10.0.0.jar:[path-to-all-other-dependency-jars]" com.mycompany.app.App

Only use this for quick one-off tests—stick to the first two fixes for regular use.

内容的提问来源于stack exchange,提问作者Byron Hsu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:47:30