groovy 脚本类路径 [英] groovy script classpath

查看:40
本文介绍了groovy 脚本类路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Groovy 编写脚本,我希望有人能够通过运行 ./myscript.groovy 来执行它.但是,这个脚本需要一个 3rd 方库(MySQL JDBC),我不知道除了通过 -classpath-cp 参数,例如

I'm writing a script in Groovy and I would like someone to be able to execute it simply by running ./myscript.groovy. However, this script requires a 3rd party library (MySQL JDBC), and I don't know of any way to provide this to the script other than via a -classpath or -cp argument, e.g.

`./monitor-vouchers.groovy -cp /path/to/mysql-lib.jar`

由于我不会在这里讨论的原因,实际上不可能使用 -classpath/-cp 参数为脚本提供 JAR 位置.有什么方法可以从脚本本身加载 JAR?我尝试使用 @Grab

For reasons I won't go into here, it's not actually possible to provide the JAR location to the script using the -classpath/-cp argument. Is there some way that I can load the JAR from within the script itself? I tried using @Grab

import groovy.sql.Sql


@Grab(group='mysql', module='mysql-connector-java', version='5.1.19')
def getConnection() {
    def dbUrl = 'jdbc:mysql://database1.c5vveqm7rqgx.eu-west-1.rds.amazonaws.com:3306/vouchers_prod'
    def dbUser = 'pucaroot'
    def dbPassword = 'password'
    def driverClass = "com.mysql.jdbc.Driver"

    return Sql.newInstance(dbUrl, dbUser, dbPassword, driverClass)
}

getConnection().class

但这会导致以下错误:

Caught: java.sql.SQLException: No suitable driver
java.sql.SQLException: No suitable driver
        at monitor-vouchers.getConnection(monitor-vouchers.groovy:13)
        at monitor-vouchers.run(monitor-vouchers.groovy:17)

有没有办法只使用 ./monitor-vouchers.groovy

推荐答案

你应该能够做到:

import groovy.sql.Sql

@GrabConfig(systemClassLoader=true)
@Grab('mysql:mysql-connector-java:5.1.19')
def getConnection() {
    def dbUrl = 'jdbc:mysql://database1.c5vveqm7rqgx.eu-west-1.rds.amazonaws.com:3306/vouchers_prod'
    def dbUser = 'pucaroot'
    def dbPassword = 'bigsecret'
    def driverClass = "com.mysql.jdbc.Driver"

    return Sql.newInstance(dbUrl, dbUser, dbPassword, driverClass)
}

getConnection().class

这篇关于groovy 脚本类路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆