Using a Groovy class defined in buildSrc - get java.lang.NoClassDefFoundError:

I have a multi project build in one of the sub-projects I would like to use some Groovy classes. After looking through the docs I created the buildSrc/src/main/groovy in the root project and placed a Groovy classes in there, see below

import org.yaml.snakeyaml.Yaml
  class DatabaseHelper {
      DatabaseHelper(){
        Database targetTestDatabase
        String databasesYaml = getLocalResource('databases.yaml')
        Yaml beanLoader = new Yaml()
        databases = beanLoader.loadAs(databasesYaml, HashMap.class)
    }
}

Interestingly I do not declare any dependencies for org.yaml.snakeyaml.Yaml in the root project but build for buildSrc seems to work fine

:buildSrc:compileJava UP-TO-DATE
:buildSrc:compileGroovy
:buildSrc:processResources
:buildSrc:classes
:buildSrc:jar
:buildSrc:assemble
:buildSrc:compileTestJava UP-TO-DATE
:buildSrc:compileTestGroovy UP-TO-DATE
:buildSrc:processTestResources UP-TO-DATE
:buildSrc:testClasses UP-TO-DATE
:buildSrc:test
:buildSrc:check
:buildSrc:build

In my sub project I have the below method which is called by a task

def getTargetDb(){
    def databaseHelper = new DatabaseHelper()
    Database targetTestDatabase = databaseHelper.targetTestDatabase
    return targetTestDatabase
}

But when it runs I get the below

Caused by: java.lang.NoClassDefFoundError: org.yaml.snakeyaml.Yaml
 at DatabaseHelper.class$(DatabaseHelper.groovy)
 at DatabaseHelper.$get$$class$org$yaml$snakeyaml$Yaml(DatabaseHelper.groovy)
 at DatabaseHelper.getLocalResource(DatabaseHelper.groovy:50)
 at DatabaseHelper.<init>(DatabaseHelper.groovy:22)

I’ve no idea why it compiles in the first place. Any chance you could provide a sample project that exhibits the behaviour?

To make it work, you just need to add the dependency to ‘buildSrc/build.gradle’.

Can you please provide an and example what the build.gradle should look like as I tried this and still no joy

Please post what you tried.

repositories{
    maven{url "http://atlas.intranet.barclays.co.uk:8021/artifactory/remote-repos"}
}
  dependencies {
    compile 'org.yaml:snakeyaml:1.10'
}

Same result?

Yes

Something very strange is going on.

Any chance you could put together a sample project that’s doing this? I can’t reproduce it.

Sorry I’m off on holiday for 10 days wife has banned me from the computer. When I get back I will have a look.

thanks for the help

Could it be that

repositories{
    maven{url "http://atlas.intranet.barclays.co.uk:8021/artifactory/remote-repos"}
}
dependencies {
    compile 'org.yaml:snakeyaml:1.10'
}

…just needs to be wrapped in:

buildscript {
  repositories{
      maven{url "http://atlas.intranet.barclays.co.uk:8021/artifactory/remote-repos"}
  }
  dependencies {
      compile 'org.yaml:snakeyaml:1.10'
  }
}

?

If I understand what you are doing correctly, that’s not it.

That’s how you control dependencies for the build itself, not what you are building.