dependsOn (inter task dependency)

Gradle Inter-Task Dependency: dependsOn

dependsOn in Gradle defines a dependency between tasks, ensuring one task runs before another. When a task declares dependsOn, Gradle guarantees that the dependent task is executed first.

dependsOn ensures tasks execute in the correct order by defining dependencies. It's commonly used to ensure tasks that rely on outputs from other tasks run after their dependencies complete.

Usage:

  • Use dependsOn to specify that a task depends on one or more other tasks.

  • Gradle will always execute the dependent tasks before the task that declares the dependency.

    Example:

    tasks.register("compile") {
        doLast {
            println("Compiling code...")
        }
    }
    
    tasks.register("build-stuff") {
        dependsOn("compile")  // 'build' will run after 'compile'
        doLast {
            println("Building project...")
        }
    }
    
Glass thought Sandbox Snapshot

Command to reproduce:

gt.sandbox.checkout.commit ef515ba \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew build-stuff"

Recorded output of command:


> Task :lib:compile
Compiling code...

> Task :lib:build-stuff
Building project...

BUILD SUCCESSFUL in 350ms
2 actionable tasks: 2 executed

Key Points:

  • You can add multiple dependencies using dependsOn.
  • Dependencies are executed in the order they are declared.
  • The dependent tasks must complete successfully before the task with dependsOn runs.
  • If any dependent task is skipped, failed, or up-to-date, the task still respects the dependency state.

Backlinks