How do you configure GroovyConsole so I don't have to import libraries at startup?

前端 未结 5 1898
长发绾君心
长发绾君心 2021-02-06 04:44

I have a groovy script that uses a third party library. Each time I open the application and attempt to run my script I have to import the proper library.

I would lik

5条回答
  •  再見小時候
    2021-02-06 05:39

    You can write an external Groovy script that does all the imports, creates a GroovyConsole object, and calls the run() method on this object.

    See also http://groovy.codehaus.org/Groovy+Console#GroovyConsole-EmbeddingtheConsole

    For example: start.groovy

    import groovy.ui.Console;
    
    import com.botkop.service.*
    import com.botkop.service.groovy.*
    
    def env = System.getenv()
    def service = new ServiceWrapper(
      userName:env.userName, 
      password:env.password, 
      host:env.host, 
      port:new Integer(env.port))
    
    service.connect()
    
    Console console = new Console()
    console.setVariable("service", service)
    console.run()
    

    From a shell script call the groovy executable providing it with the groovy script:

    #!/bin/bash
    
    if [ $# -ne 4 ]
    then 
      echo "usage: $0 userName password host port"
      exit 10
    fi
    
    export userName=$1
    export password=$2
    export host=$3
    export port=$4
    
    export PATH=~/apps/groovy/bin:/usr/bin:$PATH
    export CLASSPATH=$(find lib -name '*.jar' | tr '\n' ':')
    
    groovy start.groovy
    

    The code in GroovyConsole can now make use of the imports done in start.groovy, as well as of the variables created and passed with the setVariable method ('service' in the example).

提交回复
热议问题