使用Gradle Kotlin DSL打包普通Jar

gradle 和 kotlin一直是我比较常用的组合方式,也算是稍微新一点都技术选型,国内相关使用资料并没有maven的普遍,Gradle Kotlin DSL也都是一些外文资料,本篇介绍一下普通项目的打包配置。

官方文档 https://docs.gradle.org/current/userguide/kotlin_dsl.html

在项目没有引用springboot的情况下,是无法使用springboot为我们准备好的bootJar的,打包也需要自己配置

如果直接运行 gradle jar ,会发现打包成功,但是无法运行,只有一个空包,运行提示xxx.jar中没有主清单属性

image-20210509112708478

普通打包方式

我们在build.gradle.kts中为打包加上主清单,注意:使用kotlin需要在main方法所在文件名最后加上Kt

tasks.jar {
    // enabled = true
    manifest {
        attributes(mapOf("Main-Class" to "com.xx.xx.ci.MainKt"))
    }
}

继续执行打包,运行后发现一些错误信息,大意是没有将相关jar包打入当前包

image-20210509113644408

最终配置,这个配置不仅可以将当前程序的依赖打入jar,还能将依赖jar的依赖打入,也就实现了将嵌套依赖打入最终包中

tasks.jar {
    // enabled = true
    manifest {
        attributes(mapOf("Main-Class" to "com.xx.xx.ci.MainKt"))
    }
    from(configurations.runtimeClasspath.get().map {
        if (it.isDirectory) it else zipTree(it)
    })
    val sourcesMain = sourceSets.main.get()
    sourcesMain.allSource.forEach { println("add from sources: ${it.name}") }
    from(sourcesMain.output)
}
posted @ 2021-05-09 11:53  tsvico  阅读(2201)  评论(7编辑  收藏  举报