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

后端 未结 7 1726
余生分开走
余生分开走 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 16:49

    You can declare common dependencies in a parent script:

    ext.libraries = [ // Groovy map literal
        spring_core: "org.springframework:spring-core:3.1",
        junit: "junit:junit:4.10"
    ]
    

    From a child script, you can then use the dependency declarations like so:

    dependencies {
        compile libraries.spring_core
        testCompile libraries.junit
    }
    

    To share dependency declarations with advanced configuration options, you can use DependencyHandler.create:

    libraries = [
        spring_core: dependencies.create("org.springframework:spring-core:3.1") {
            exclude module: "commons-logging"
            force = true
        }
    ]
    

    Multiple dependencies can be shared under the same name:

    libraries = [
        spring: [ // Groovy list literal
            "org.springframework:spring-core:3.1", 
            "org.springframework:spring-jdbc:3.1"
        ]
    ]
    

    dependencies { compile libraries.spring } will then add both dependencies at once.

    The one piece of information that you cannot share in this fashion is what configuration (scope in Maven terms) a dependency should be assigned to. However, from my experience it is better to be explicit about this anyway.

提交回复
热议问题