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

后端 未结 7 1650
余生分开走
余生分开走 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:08

    To keep you gradle file clean, we can group dependency in an array and implement them later.

    1. Add version of libraries like this in build.gradle (app level) outside of dependency block:

    // declare versions of library

    final RetrofitVersion = '2.3.0'
    final OkHttpVersion = '3.9.1'
    
    1. Create an array of related dependency, so you can easily find it later. Add it in build.gradle (app level) outside of dependency block:

    // Using version in library and add dependency along with access name(like retrofit(first one))

    final networkDependencies = [
            retrofit             : "com.squareup.retrofit2:retrofit:${RetrofitVersion}",
            retrofitGsonConverter: "com.squareup.retrofit2:converter-gson:${RetrofitVersion}",
            retrofitRxJavaAdapter: "com.squareup.retrofit2:adapter-rxjava2:${RetrofitVersion}",
            okHttp3              : "com.squareup.okhttp3:okhttp:${OkHttpVersion}",
            okHttp3Logging       : "com.squareup.okhttp3:logging-interceptor:${OkHttpVersion}"
    ]
    
    1. And in dependency block:

    // Implement all the dependency from array

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

    So the final code will look like this:

    final RetrofitVersion = '2.3.0'
    final OkHttpVersion = '3.9.1'
    
    final networkDependencies = [
            retrofit             : "com.squareup.retrofit2:retrofit:${RetrofitVersion}",
            retrofitGsonConverter: "com.squareup.retrofit2:converter-gson:${RetrofitVersion}",
            retrofitRxJavaAdapter: "com.squareup.retrofit2:adapter-rxjava2:${RetrofitVersion}",
            okHttp3              : "com.squareup.okhttp3:okhttp:${OkHttpVersion}",
            okHttp3Logging       : "com.squareup.okhttp3:logging-interceptor:${OkHttpVersion}"
    ]
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
    
        implementation networkDependencies.values()
    }
    
    0 讨论(0)
提交回复
热议问题