Search code examples
gradlegradle-kotlin-dsl

How to add dependency to configuration in gradle plugin


I'm developing Gradle custom plugin. I want to add dependency to the existing configuration. I'm trying to do it like this:

open class MyApplicationExtension @Inject constructor(objects: ObjectFactory) {
  val version: Property<String> = objects.property(String::class)
}

class MyApplicationPlugin : Plugin<Project> {
  override fun apply(project: Project) {
    project.plugins.apply(ApplicationPlugin::class)
    val extension = project.extensions.create<MyApplicationExtension>("myApp")
    val implConfig = project.configurations["implementation"]
    implConfig.defaultDependencies {
      add(project.dependencies.create("com:my-app:${extension.version.get()}"))
    }
  }
}

But when I try to use application in gradle project the added dependency is not added. I'm trying to use it like this:

apply<MyApplicationPlugin>()
the<MyApplicationExtension>().version.set("0.1.0")

dependencies {
  // This overrides the default dependencies
  implementation("com:another:0.2.0")
}

And when I invoke dependencies task my dependency is not shown there. So how to add configurable dependency to the implementation configuration from custom plugin? Running with Gradle 5.3.1 in Kotlin DSL.


Solution

  • Default dependencies are only used if no other dependency is added to the configuration.

    Since that does not seem to be your use case, you should simply add the dependency in a normal fashion.

    implConfig.defaultDependencies {
      add(project.dependencies.create("com:my-app:${extension.version.get()}"))
    }
    

    needs to become

    implConfig.dependencies.add(project.dependencies.create("com:my-app:${extension.version.get()}"))