Ghiloufi
Ghiloufi

Reputation: 321

GroovyShell and the classpath

I'm starting to program with groovy and I wanted to know when I use GroovyShell (new File ("script.groovy"). txt) .evaluate (), do script classes see dependencies in classpath or not, i try this example and it generate the following errors.

// main.groovy

@Grapes([
    @Grab(group='org.slf4j', module='slf4j-api', version='1.6.1'),
    @Grab(group='ch.qos.logback', module='logback-classic', version='0.9.28')
])

import groovy.lang.GroovyShell;
import java.io.File;

new GroovyShell().evaluate(new File("C:\\Users\\Dev\\Desktop\\logger.groovy").text);
// logger.groovy
import org.slf4j.*
import groovy.util.logging.Slf4j

@Slf4j
class HelloWorldSlf4j {
    def execute() {
        log.debug 'Execute HelloWorld.'
        log.info 'Simple sample to show log field is injected.'
    }
}

def helloWorld = new HelloWorldSlf4j()
helloWorld.execute()
Caused by: java.lang.ClassNotFoundException: org.slf4j.Logger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:869)
    at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:979)
    at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:967)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.codehaus.groovy.transform.LogASTTransformation$AbstractLoggingStrategy.classNode(LogASTTransformation.java:346)
    ... 38 more

Upvotes: 2

Views: 1203

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

If you want logger.groovy file to use the same classloader as main.groovy script, you need to pass it with the GroovyShell constructor. You can get the current classloader by calling this.class.classLoader.

@Grapes([
    @Grab(group='org.slf4j', module='slf4j-api', version='1.6.1'),
    @Grab(group='ch.qos.logback', module='logback-classic', version='0.9.28')
])

import groovy.lang.GroovyShell
import java.io.File

new GroovyShell(this.class.classLoader).evaluate(new File("logger.groovy"))

Output:

$ groovy main.groovy
16:17:11.325 [main] DEBUG HelloWorldSlf4j - Execute HelloWorld.
16:17:11.327 [main] INFO  HelloWorldSlf4j - Simple sample to show log field is injected.

Upvotes: 2

Related Questions