Gradle: How to add dependencies for all sourceSets?

Viewed 163

I have a multi-soruceSets project, but I failed to add local jar dependencies for all sourceSets.

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'java'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

sourceSets {
    annotations {
        java.srcDirs = ["src/annotations"]
        java.outputDir = file("${buildDir}/annotations")
    }
    main {
        java.srcDirs = ["src/main"]
        java.outputDir = file("${buildDir}/main")
        compileClasspath += sourceSets.annotations.output
    }
    classes {
        java.srcDirs = ["src/classes"]
        java.outputDir = file("${buildDir}/classes")
        compileClasspath += sourceSets.main.output + sourceSets.annotations.output
    }
    examples {
        java.srcDirs = ["src/examples"]
        java.outputDir = file("${buildDir}/examples")
        compileClasspath += sourceSets.main.output + sourceSets.classes.output
    }
    peers {
        java.srcDirs = ["src/peers"]
        java.outputDir = file("${buildDir}/peers")
        compileClasspath += sourceSets.main.output + sourceSets.annotations.output
    }
    test {
        java.srcDirs = ["src/tests"]
        java.outputDir = file("${buildDir}/tests")
        compileClasspath += sourceSets.annotations.output + sourceSets.classes.output + sourceSets.peers.output
        runtimeClasspath += compileClasspath
    }
}

dependencies {
    // Use JUnit Jupiter for testing.
    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'

    // This dependency is used by the application.
    implementation 'com.google.guava:guava:30.1.1-jre'

    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

task compile {
    println '--------'
    println sourceSets.classes.getCompileClasspath().asPath
    println '--------'
    dependsOn compileTestJava
    dependsOn compileExamplesJava
}

When I run the compile task, the terminal shows the compileClassPath for sourceSet classes, and the local dependencies dir libs are not included. I found that it is only included in sourceSet main's compileClassPath. So I wonder is there anyway efficient way to add local jar dependencies for all sourceSets? I don't want to add such statement compileClasspath += sourceSets.main.compileClasspath for all sourceSets.

Thanks in advance.

0 Answers
Related