编译一个 groovy 脚本及其所有由 gradle 管理的依赖项,然后 运行 通过命令行将其作为独立应用程序

Compile a groovy script with all it's dependencies which are managed by gradle and then run it as a standalone application via the command line

我有一个简单的 groovy 脚本,只有一个 java 库依赖项:

package com.mrhacki.myApp

import me.tongfei.progressbar.ProgressBar

    class Loading {        
        static void main(String[] arguments) {        
            List list = ["file1", "file2", "file3"]        
            for (String x : ProgressBar.wrap(list, "TaskName")) {
                println(x)
            }        
        }
    }

我正在使用 gradle 来管理项目的依赖项。该项目的 gradle 配置也非常简单:

plugins {
    id 'groovy'
}

group 'com.mrhacki'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    compile 'me.tongfei:progressbar:0.7.2'
}  

如果我 运行 来自 Intellij IDE 的脚本,脚本将按预期执行。

我现在想做的是将具有此依赖关系的脚本编译成一个 .jar 文件,这样我就可以这样分发它,运行 来自任何文件系统路径的应用程序,作为脚本逻辑将取决于调用执行的路径。

我尝试了一些 gradle fat jars 示例,但是 none 对我有用,因为 .jar 文件在我尝试时不断抛出 Could not find or load main class Loading 运行.

如果有人愿意提供提示或展示一个 gradle 任务的示例,该任务可以执行符合我描述的需求的构建,我将非常感激。

我也知道带有 @Grab 注释的 groovy 模块 Grape,但我会把它作为最后的手段,因为我不希望用户等待依赖项下载,并希望将它们与应用程序捆绑在一起。

我正在为项目使用 groovy 2.5.6 和 gradle 4.10

谢谢

您可以简单地自己创建 fat-jar,无需任何额外的插件,使用 jar 任务。对于像您这样的 simple/small 项目,它应该很简单:

jar {
    manifest {
        // required attribute "Main-Class"
        attributes "Main-Class": "com.mrhacki.myApp.Loading"
    }

    // collect (and unzip) dependencies into the fat jar
    from {
        configurations.compile.collect { 
            it.isDirectory() ? it : zipTree(it) 
        }
    }
}

编辑:请考虑其他评论:如果您有一个以上的外部库,您可能会遇到此解决方案的问题,因此在这种情况下您应该寻求使用 "shadow" 插件的解决方案。