Share code between Gradle buildSrc and project

Viewed 1185

Suppose I have some classes containing logic that I would like to use during the Gradle build and in the Java application itself. How can configure a Gradle build to share the same classes between a build and the project that is being built, for example using the Kotlin DSL?

2 Answers

You can just add the shared classes in buildSrc to your application classpath like so:

sourceSets["main"].compileClasspath += files("${project.rootDir}/buildSrc/build/")

As @lance-java mentions, you should also add a compile dependency:

dependencies {
  compile(fileTree("${project.rootDir}/buildSrc/build/"))
}

Finally, if a class you need to use imports from org.gradle.api, add this line to dependencies:

compile(gradleApi())

Inspired by @breandan's answer, I think it's better as:

apply plugin: 'java' 
dependencies {
    compile files("${project.rootDir}/buildSrc/build/classes/" )
} 
Related