ha9u63a7
ha9u63a7

Reputation: 6862

Gradle - cannot load a Java Class even when packed within the jar

My gradle build file is

plugins {
    // Apply the java plugin to add support for Java
    id 'java'

    // Apply the application plugin to add support for building a CLI application
    id 'application'
}

apply plugin: 'java'
jar {
    from configurations.runtime
    manifest {
        attributes(
            'Created-By':'Gmack',
            'Main-Class':'myapprunner.App',
            'Class-Path':'mydaos-1.0.jar'
        )

    }

}

allprojects{

  repositories {
      jcenter()
  }
}

subprojects {
   version = '1.0'
   apply plugin: 'java'
}

dependencies {
    // This dependency is used by the application.
    implementation 'com.google.guava:guava:27.1-jre'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'

    // Compile Project for dependency
    compile project(':mydaos')
}

application {
    // Define the main class for the application
    mainClassName = 'myapprunner.App'
}

When I run the app using java -jar myapprunner.jar

I get a ClassNotFoundException

Caused by: java.lang.ClassNotFoundException: com.mydaos.Library
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 1 more

I can confirm that the jar has been packed. Not sure why this is not picking things up.

Any help would be appreciated.

Thanks,

Upvotes: 0

Views: 992

Answers (2)

lance-java
lance-java

Reputation: 28101

Dependency classes (projects/external jars) aren't packed inside your jar by default.

You are using the application plugin which bundles your classes, your dependencies and an execution script in a zip so you should use that. The plugin also adds a "run" task to your project to run your main class via gradle for development purposes. See the application plugin docs for more info

If you want to pack your dependencies inside your jar (known as an uber jar) see here. I suggest you stop using the application plugin if you do this

'Class-Path':'mydaos-1.0.jar'

This assumes that mydaos-1.0.jar is in the same folder you are running java -jar ... from which is likely not the case

Upvotes: 0

Martin Zeitler
Martin Zeitler

Reputation: 76849

Plugin java is being applied twice and com.mydaos.Library is likely being pulled in from compile project(':mydaos') (or 'Class-Path':'mydaos-1.0.jar'). Would assume the project does not build or the class path is wrong.

Upvotes: 1

Related Questions