【android】Gradle配置之ResolutionStrategy

我们先看官方的介绍:
点我查看ResolutionStrategy官方原文介绍

Defines the strategies around dependency resolution. For example, forcing certain dependency versions, substitutions, conflict resolutions or snapshot timeouts.

Examples:

apply plugin: 'java' //so that there are some configurations

configurations.all {
  resolutionStrategy {
    // fail eagerly on version conflict (includes transitive dependencies)
    // e.g. multiple different versions of the same dependency (group and name are equal)
    failOnVersionConflict()

    // prefer modules that are part of this build (multi-project or composite build) over external modules
    preferProjectModules()

    // force certain versions of dependencies (including transitive)
    //  *append new forced modules:
    force 'asm:asm-all:3.3.1', 'commons-io:commons-io:1.4'
    //  *replace existing forced modules with new ones:
    forcedModules = ['asm:asm-all:3.3.1']

    // add dependency substitution rules
    dependencySubstitution {
      substitute module('org.gradle:api') with project(':api')
      substitute project(':util') with module('org.gradle:util:3.0')
    }

    // cache dynamic versions for 10 minutes
    cacheDynamicVersionsFor 10*60, 'seconds'
    // don't cache changing modules at all
    cacheChangingModulesFor 0, 'seconds'
  }
}
// add dependency substitution rules
configurations.all {
  resolutionStrategy.dependencySubstitution {
    // Substitute project and module dependencies
    substitute module('org.gradle:api') with project(':api')
    substitute project(':util') with module('org.gradle:util:3.0')

    // Substitute one module dependency for another
    substitute module('org.gradle:api:2.0') with module('org.gradle:api:2.1')
  }
}
configurations {
  compile.resolutionStrategy {
    eachDependency { DependencyResolveDetails details ->
      //specifying a fixed version for all libraries with 'org.gradle' group
      if (details.requested.group == 'org.gradle') {
        details.useVersion '1.4'
      }
    }
    eachDependency { details ->
      //multiple actions can be specified
      if (details.requested.name == 'groovy-all') {
         //changing the name:
         details.useTarget group: details.requested.group, name: 'groovy', version: details.requested.version
      }
    }
  }
}

最后我们在看一个在实际项目当中的应用吧,比如统一替换SupportVersion版本:

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion SupportVersion
            }
        }
    }
}

如果文章当中有任何不正确的地方,还请广大读者纠正,非常感谢!

    原文作者:当时不是寻常
    原文地址: https://www.jianshu.com/p/0a60a78648bf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞