Creating Runnable Jar with Gradle

Creating runnable JAR with Gradle

An executable jar file is just a jar file containing a Main-Class entry in its manifest. So you just need to configure the jar task in order to add this entry in its manifest:

jar {
manifest {
attributes 'Main-Class': 'com.foo.bar.MainClass'
}
}

You might also need to add classpath entries in the manifest, but that would be done the same way.

See http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

How can I create single executable jar in my gradle project

I am able to build a single jar, after modifying the build.gradle likes the following,

build.gradle,

plugins {
id 'com.google.cloud.tools.jib' version '2.2.0'
}

repositories {
mavenLocal()
mavenCentral()
jcenter()
}

jib.to.image = 'gcr.io/' + project.property('gcpProjectId') + '/my-application'
jib.container.creationTime = 'USE_CURRENT_TIMESTAMP'

jar {
manifest {
attributes 'Main-Class': 'com.foo.Myapplication'
}

from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}

How do I create an executable fat JAR with Gradle with implementation dependencies?

You can use the following code.

jar {
manifest {
attributes(
'Main-Class': 'com.package.YourClass'
)
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}

Be sure to replace com.package.YourClass with the fully qualified class name containing static void main( String args[] ).

This will pack the runtime dependencies. Check the docs if you need more info.

How to create executable JAR with Gradle?

Basically there are two possibilities:

  1. Application plugin, provided by gradle. Basically it prepares jar and a handful of scripts to run it.
  2. Shadow plugin which prepares an uberjar, a runnable, repackaged artifact with all the dependencies required.

Gradle task to create fat runnable jar

I could achieve this by creating a task which does the following things

  • Update manifest file with the Main-Class attributes

  • Copy all compile time dependencies to the jar task

    plugins {
    id 'application'
    }
    repositories {
    mavenCentral()
    //jcenter()
    }
    dependencies {
    compile group: 'org.json', name: 'json', version: '20200518'
    testImplementation 'junit:junit:4.13'
    implementation 'com.google.guava:guava:29.0-jre'
    }
    task fatJar(type: Jar) {

    manifest {
    attributes 'Main-Class': 'com.example.gradle.App'
    }
    from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    } with jar
    }

More details can be read in this article A simple java project with Gradle



Related Topics



Leave a reply



Submit