Java "java.lang.NoClassDefFoundError" in CI - Fix Missing Runtime Class
NoClassDefFoundError means the class existed when the code was compiled but is not loadable now - usually a dependency that is on the compile classpath yet absent at runtime, or a class whose static initializer already failed once.
What this error means
A run or test fails with java.lang.NoClassDefFoundError: com/example/Bar. Unlike ClassNotFoundException, the type was known at compile time, so this signals a compile-vs-runtime classpath mismatch (or a prior ExceptionInInitializerError).
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.example.Service.<init>(Service.java:12)
at com.example.ServiceTest.setUp(ServiceTest.java:21)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactoryCommon causes
Compile-only dependency missing at runtime
A library declared provided (Maven) or compileOnly (Gradle) is present for compilation but not packaged, so the runtime loader cannot find it.
A static initializer already failed
If a class threw during <clinit> once, every later load fails with NoClassDefFoundError because the class is marked erroneous. The real cause is the earlier ExceptionInInitializerError.
How to fix it
Promote the dependency to runtime scope
Ensure the artifact ships at runtime, not only for compilation.
// Gradle: implementation (not compileOnly) so it is on the runtime classpath
dependencies {
implementation 'org.slf4j:slf4j-api:2.0.13'
runtimeOnly 'org.slf4j:slf4j-simple:2.0.13'
}Look for an earlier initializer failure
- Scroll up: a
Caused by: java.lang.ExceptionInInitializerErrorearlier in the run is the true root cause. - Confirm compile and runtime classpaths agree with
mvn dependency:tree/gradle dependencies. - For shaded jars, verify the package was not relocated or stripped.
How to prevent it
- Keep
provided/compileOnlystrictly for things the runtime really supplies; verify the runtime classpath in CI and fix initializer failures at their source.