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

问题描述 投票:2回答:4

我有一个Groovy项目(使用Eclipse),它使用了几个@Grab语句。这在我的开发机器上工作正常。但是,我需要将此应用程序(包括其所有依赖项)分发给其他没有任何Internet连接的计算机,即无法从这些计算机上下载必要的JAR。

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

groovy grape
4个回答
5
投票

所以,比方说,你有一个像这样的脚本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插件将所有依赖项捆绑到一个胖胖的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文件,而不仅仅是脚本...

希望这可以帮助


1
投票

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

Grape(Groovy Adaptable Packaging Engine或Groovy Advanced Packaging Engine)是在Groovy中启用grab()调用的基础结构,Groovy是一组利用Ivy的类,允许Groovy使用存储库驱动的模块系统。这允许开发人员编写具有基本任意库要求的脚本,并仅发布脚本。 Grape将在运行时根据需要下载并链接命名库和所有依赖关系,当脚本从现有存储库(如Ibiblio,Codehaus和java.net)运行时形成传递闭包。

此链接可能有助于您过渡到使用Gradle与Groovy脚本。

Running Groovy scripts from Gradle


0
投票

您可以将Grape repo复制到目标部署服务器。应该是〜/ .groovy / Grape。然后你可以按原样保留你的@Grabs


0
投票

两种解决方案

  1. 用gradle替换整个构建进度,就像@tim_yates的回答所提到的那样。
  2. 使用grape install命令将软件包预先安装到葡萄本地仓库中,其默认路径为“〜/ .groovy / grapes”。然后将脚本和葡萄目录打包在一起。您可以将葡萄回购目录切换到您喜欢的地方。见http://docs.groovy-lang.org/latest/html/documentation/grape.html第3.5节
© www.soinside.com 2019 - 2024. All rights reserved.