Groovy script classpath

I am 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 third-party library (MySQL JDBC), and I do not know how to provide this for the script, except through the -classpath or -cp , for example.

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

For reasons that I will not go into, it is actually not possible to provide a JAR location in a script with the -classpath / -cp argument. Is there a way to load the JAR from 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 

But this causes the following error:

 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) 

Is there a way I can execute this script using only ./monitor-vouchers.groovy

+6
source share
2 answers

You must be able to:

 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 
+12
source

Two more options:

  • Put the jar in $ {user.home} /. groovy / lib
  • If the container is in a known place, use this code to load it into the current classloader:

    this.class.classLoader.rootLoader.addURL (new URL ())

+7
source

Source: https://habr.com/ru/post/915690/


All Articles