In Gradle, how do I declare common dependencies in a single place?

后端 未结 7 1702
余生分开走
余生分开走 2020-11-29 16:08

In Maven there is a very useful feature when you can define a dependency in the section of the parent POM, and reference that depen

7条回答
  •  温柔的废话
    2020-11-29 17:01

    As of Gradle 4.6, dependency constraints are suggested in the documentation as the way to achieve this. From https://docs.gradle.org/current/userguide/declaring_dependencies.html#declaring_a_dependency_without_version:

    A recommended practice for larger projects is to declare dependencies without versions and use dependency constraints for version declaration. The advantage is that dependency constraints allow you to manage versions of all dependencies, including transitive ones, in one place.

    In your parent build.gradle file:

    allprojects {
      plugins.withType(JavaPlugin).whenPluginAdded {
        dependencies {
          constraints {
            implementation("com.google.guava:guava:27.0.1-jre")
          }
        }
      }
    }
    

    Wrapping the dependencies block with a check for the Java plugin (... whenPluginAdded {) isn't strictly necessary, but it will then handle adding a non-Java project to the same build.

    Then in a child gradle project you can simply omit the verison:

    apply plugin: "java"
    
    dependencies {
      implementation("com.google.guava:guava")
    }
    

    Child builds can still choose to specify a higher version. If a lower version is specified it is automatically upgraded to the version in the constraint.

提交回复
热议问题