How to create Java Gradle project from command line?
It should create standard maven folder layout like on the picture below.
Here is what it worked for me.. I wanted to create a hello world java application with gradle with the following requirements.
Here is the solution :
gradle init --type java-application
Runnable fat Jar
task fatJar(type: Jar) {
clean
println("Creating fat jar")
manifest {
attributes 'Main-Class': 'com.abc.gradle.hello.App'
}
archiveName "${runnableJar}"
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println("Fat jar is created")
}
Copy Dependencies
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
Create jar with classpath dependecies in manifest
task createJar(type: Jar) {
println("Cleaning...")
clean
manifest {
attributes('Main-Class': 'com.abc.gradle.hello.App',
'Class-Path': configurations.default.collect { 'dependencies/' +
it.getName() }.join(' ')
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println "${outputJar} created"
}
Here is the complete build.gradle
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.slf4j:slf4j-api:1.7.30'
implementation 'ch.qos.logback:logback-classic:1.2.3'
implementation 'ch.qos.logback:logback-core:1.2.3'
testImplementation 'junit:junit:4.13'
}
def outputJar = "${buildDir}/libs/${rootProject.name}.jar"
def dependsDir = "${buildDir}/libs/dependencies/"
def runnableJar = "${rootProject.name}_fat.jar";
//Create runnable fat jar
task fatJar(type: Jar) {
clean
println("Creating fat jar")
manifest {
attributes 'Main-Class': 'com.abc.gradle.hello.App'
}
archiveName "${runnableJar}"
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println("Fat jar is created")
}
//Copy dependent libraries to directory.
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
//Create runnable jar with dependencies
task createJar(type: Jar) {
println("Cleaning...")
clean
manifest {
attributes('Main-Class': 'com.abc.gradle.hello.App',
'Class-Path': configurations.default.collect { 'dependencies/' +
it.getName() }.join(' ')
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println "${outputJar} created"
}
Gradle build commands
Create fat jar : gradle fatJar
Copy dependencies : gradle copyDepends
Create runnable jar with dependencies : gradle createJar
More details can be read here : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d
To create a Java project: create a new project directory, jump into it and execute
gradle init --type java-library
Source folders and a Gradle build file (including a wrapper) will be build.