在没有存储库访问权限的 Groovy 应用程序中包含依赖项

Include dependencies in Groovy application without repository access

我有一个 Groovy 项目(使用 Eclipse),它使用了几个 @Grab 语句。这在我的开发机器上运行良好。但是,我需要将此应用程序(包括其所有依赖项)分发到没有任何互联网连接的其他机器,即无法从这些机器下载必要的 JAR。

有没有办法以某种方式自动将依赖项包含到项目中,例如lib 文件夹?这样我就可以将项目复制到另一台机器上并使用它。

我建议切换到 Gradle 或其他一些在构建时下载依赖项的构建工具。正如您可能已经知道的那样,葡萄会在运行时删除所有依赖项。

Grape (The Groovy Adaptable Packaging Engine or Groovy Advanced Packaging Engine) is the infrastructure enabling the grab() calls in Groovy, a set of classes leveraging Ivy to allow for a repository driven module system for Groovy. This allows a developer to write a script with an essentially arbitrary library requirement, and ship just the script. Grape will, at runtime, download as needed and link the named libraries and all dependencies forming a transitive closure when the script is run from existing repositories such as Ibiblio, Codehaus, and java.net.

此 link 可能会帮助您过渡到将 Gradle 与 Groovy 脚本一起使用。

Running Groovy scripts from Gradle

所以,假设你有一个像这样的脚本 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 中,放入这个脚本来拉下 groovygroovy-wslite 依赖项,并应用 shadow-jar 插件将所有依赖项捆绑到一个单一的 fat 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 文件,而不仅仅是脚本...

希望对您有所帮助

您可以将 Grape 存储库复制到目标部署服务器。应该是~/.groovy/Grape。然后你可以将你的@Grabs 保持在脚本中

两种解决方案

  1. 将整个构建进度替换为gradle,就像@tim_yates'回答中提到的那样。

  2. 使用grape install命令将包预安装到grape本地仓库中,默认路径为“~/.groovy/grapes”。然后打包脚本和葡萄目录在一起。你可以将 grape repo 目录切换到你喜欢的地方。请参阅 http://docs.groovy-lang.org/latest/html/documentation/grape.html

  3. 的第 3.5 节