因此,假设您有一个脚本 Script.groovy 像这样,您当前使用 groovy Script.groovy 运行:
@Grab('com.github.groovy-wslite:groovy-wslite:1.1.2')
import wslite.rest.*
def client = new RESTClient("http://httpbin.org")
def response = client.get(path:'/get')
assert 200 == response.statusCode
println "Received : $response.json"
现在,我们希望将其放入一个 jar 文件中,您可以分发,人们可以使用 java -jar myApp.jar 运行
所以制作如下文件夹结构:
myApp
|-- src
| |-- main
| |-- groovy
| |-- example
| |-- Script.groovy
|-- build.gradle
然后,在Script.groovy 中,放入你的脚本(带有包名,没有@Grab 注释):
package example
import wslite.rest.*
def client = new RESTClient("http://httpbin.org")
def response = client.get(path:'/get')
assert 200 == response.statusCode
println "Received : $response.json"
在build.gradle 中,放置这个脚本,它会拉下groovy 和groovy-wslite 依赖项,并应用shadow-jar 插件将所有依赖项捆绑到一个单独的胖jar 中:
plugins {
id "com.github.johnrengelman.shadow" version "1.2.2"
}
apply plugin: 'groovy'
apply plugin: 'application'
repositories {
jcenter()
}
mainClassName = 'example.Script'
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.5'
compile 'com.github.groovy-wslite:groovy-wslite:1.1.2'
}
然后您可以(假设您已经安装了 Gradle),只需运行:
gradle shadowJar
它将编译您的代码,并将其及其所有依赖项放入build/libs/myApp-all.jar
那么,你可以运行:
java -jar build/libs/myApp-all.jar
您的脚本应该像以前一样运行...
然后您可以分发此 jar 文件,而不仅仅是脚本...
希望对你有帮助