这对我有用。我想用 gradle 创建一个 hello world java 应用程序,并满足以下要求。
- 应用程序具有外部 jar 依赖项
- 创建一个可运行的胖 jar,并将所有依赖类复制到 jar
- 创建一个可运行的 jar,将所有依赖库复制到目录“dependencies”,并在清单中添加类路径。
这是解决方案:
- 安装最新的 gradle(检查 gradle --version 。我用的是 gradle 6.6.1)
- 创建文件夹并打开终端
- 执行
gradle init --type java-application
- 在命令行中添加所需数据
- 将项目导入 IDE(IntelliJ 或 Eclipse)
- 使用以下任务编辑 build.gradle 文件。
可运行的脂肪罐
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")
}
复制依赖
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
在清单中创建具有类路径依赖项的 jar
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"
}
这是完整的 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 构建命令
创建 fat jar:gradle fatJar
复制依赖项:gradle copyDepends
创建具有依赖项的可运行 jar:gradle createJar
更多细节可以在这里阅读:https ://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d