Grape 依赖管理器

本文参考自Groovy文档 The Grape dependency manager,本文代码大部分来自Groovy官方文档。

Groovy自带了一个嵌入式的jar依赖管理器,这个管理器的主要作用应该是配合Groovy脚本使用,让我们不需要任何额外配置就可以执行Groovy脚本。

快速开始

我们只要在Groovy文件的导入声明上添加@Grab注解即可,在注解上我们需要添加Maven依赖的相关信息。依赖项默认情况下会从Maven中央仓库下载。

@Grab(group='org.springframework', module='spring-orm', version='3.2.5.RELEASE')
import org.springframework.jdbc.core.JdbcTemplate

也可以使用简略形式。

@Grab('org.springframework:spring-orm:3.2.5.RELEASE')

如果希望使用其他Maven仓库,可以使用GrabResolver注解,指定要使用的仓库URL。下面指定了阿里的仓库。

@GrabResolver(name='aliyun', root='http://maven.aliyun.com/nexus/content/groups/public/')
@Grab(group='org.restlet', module='org.restlet', version='1.1.6')

如果不需要某个传递依赖,可以排除它。

@Grab('net.sourceforge.htmlunit:htmlunit:2.8')
@GrabExclude('xml-apis:xml-apis')

JDBC驱动需要使用系统类加载器加载,所以需要让Grape将依赖项链接到系统类加载器上。

@GrabConfig(systemClassLoader=true)
@Grab(group='mysql', module='mysql-connector-java', version='5.1.40')

如果需要在一个节点上声明多个依赖,需要使用@Grapes注解。

@Grapes([
   @Grab(group='commons-primitives', module='commons-primitives', version='1.0'),
   @Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')])
class Example {
// ...
}

配置

代理配置

要使用代理,可以在执行Groovy脚本的时候指定代理。

groovy -Dhttp.proxyHost=yourproxy -Dhttp.proxyPort=8080 yourscript.groovy

或者配置JAVA_OPTS环境变量。

JAVA_OPTS = -Dhttp.proxyHost=yourproxy -Dhttp.proxyPort=8080

缓存位置

默认情况下依赖项会下载到~/.groovy/grape,我们也可以使用其他位置。

groovy -Dgrape.root=/repo/grape yourscript.groovy

命令行工具

Groovy还提供了命令行工具grape来管理Grape依赖。

安装某个依赖。

grape install   []

列出所有依赖。

grape list

其他用法请参考Groovy文档。

更多例子

Groovy文档演示了几个例子,这里列出两个最典型的。

使用TagSoup库查找Java规范的PDF文件。

// find the PDF links of the Java specifications
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='1.2.1')
def getHtml() {
    def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
    parser.parse("https://docs.oracle.com/javase/specs/")
}
html.body.'**'[email protected](~/.*\.pdf/).each{ println it }

开启Jetty服务器。

@Grapes([
    @Grab(group='org.eclipse.jetty.aggregate', module='jetty-server', version='8.1.7.v20120910'),
    @Grab(group='org.eclipse.jetty.aggregate', module='jetty-servlet', version='8.1.7.v20120910'),
    @Grab(group='javax.servlet', module='javax.servlet-api', version='3.0.1')])

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.*
import groovy.servlet.*

def runServer(duration) {
    def server = new Server(8080)
    def context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    context.resourceBase = "."
    context.addServlet(TemplateServlet, "*.gsp")
    server.start()
    sleep duration
    server.stop()
}

runServer(10000)

你可能感兴趣的:(Grape 依赖管理器)