Classes in buildSrc throws NoClassDefFoundError on dependencies defined in gradle script


(detlef.brendle) #1

Hi, I have the following gradle script:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath(group: 'commons-io', name: 'commons-io', version: '2.0.1')
    }
}
task helloCommons << {
    new MyWriter().write()
}

and a basic class in buildSrc/src/main/groovy/MyWriter.groovy

import org.apache.commons.io.FileUtils
  class MyWriter {
    void write() {
        FileUtils.writeStringToFile(new File('test.txt'),"hello")
    }
}

When running gradle helloCommons it throws a NoClassDefFoundError

Build file '/home/detlef/develop/gradle/my.gradle' line: 11
  * What went wrong:
Execution failed for task ':helloCommons'.
Cause: java.lang.NoClassDefFoundError: org.apache.commons.io.FileUtils

When writing in build.gradle:

task helloCommons << {
    org.apache.commons.io.FileUtils.writeStringToFile(new File('test.txt'),"hello")
}

it work, but why doesnt it work when extracting that to a class ?

Can somebody spot my problem here ? Thanks

detlef


(Peter Niederwieser) #2

You need to add a ‘build.gradle’ for the ‘buildSrc’ project, and add commons-io as a ‘compile’ dependency.


(detlef.brendle) #3

Thanks, this work perfect.