Reputation: 81
I'm new to gradle.
I have Java projects, with maven dependencies and local Java archive dependencies. I want to build an independent jar which includes my code and all dependencies.
I've tried
dependencies {
runtime files(...)
runtime group ...
}
to make libraries available when I run the program later, but it doesn't work, they are not available at runtime...
I also tried this:
from("$projectDir") {
include '../lib/**';
}
but no success...the java program can't find the dependencies (NoClassDefFoundError) when I run it.
Upvotes: 3
Views: 13174
Reputation: 15193
Works on gradle 5, as is:
task buildJar(type: Jar) {
manifest {
attributes(
'Main-Class': 'org.mycompany.mainclass'
)
}
classifier = 'all'
baseName = 'MyJar'
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
{
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
with jar
}
Jar will be placed at ./build/libs
Upvotes: 3
Reputation: 709
To answer your question:
I want to build an independent jar which includes my code and all dependencies.
It sounds like you're asking how to build a "fat jar" in Gradle. You can do this with the JAR task like so:
jar {
from {configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
...
}
That first line of code basically states to "jar up" all the configured dependencies under the "compile" dependency configuration. Obviously, if you had different dependencies in other dependency configurations that you wanted to include, you would include them as well or in place of, i.e.
configurations.runtime.collect { ... }
After running your build task or any tasks that creates the JAR, you should find all your project's dependency JARs in that respective archive.
Upvotes: 5