如何让Gradle依赖转换忽略内部项目及组内指定库?
解决方案
方法1:通过解析策略移除特定依赖的属性要求
核心思路是在全局配置属性要求的同时,对内部子项目和指定组的库单独移除minified属性约束,避免解析失败:
def artifactType = Attribute.of('artifactType', String) def minified = Attribute.of('minified', Boolean) dependencies { attributesSchema { attribute(minified) } artifactTypes.getByName("jar") { attributes.attribute(minified, false) } } configurations.all { afterEvaluate { if (canBeResolved) { attributes.attribute(minified, true) resolutionStrategy { componentSelection { all { selection -> def candidateId = selection.candidate.id // 排除内部子项目 if (candidateId instanceof ProjectComponentIdentifier) { selection.attributes { remove(minified) } } // 排除指定组的库(替换为你的目标组名) else if (candidateId instanceof ModuleComponentIdentifier && candidateId.group == "com.mycompany") { selection.attributes { remove(minified) } } } } } } } } dependencies { registerTransform(Minify) { from.attribute(minified, false).attribute(artifactType, "jar") to.attribute(minified, true).attribute(artifactType, "jar") // 可选:限制转换仅应用于外部目标库,避免对内部项目执行无意义的转换 includeDependencies { details -> def requested = details.requested !(requested instanceof ProjectComponentSelector) && !(requested instanceof ModuleComponentSelector && requested.group == "com.mycompany") } } } dependencies { implementation('com.google.guava:guava:27.1-jre') implementation(project(':my-sub-project')) }
方法2:给内部子项目添加属性(允许转换内部项目时使用)
如果不介意对内部子项目应用minify转换,可在:my-sub-project的build.gradle中添加minified属性,让其满足消费者的属性要求:
// 在my-sub-project的build.gradle中 def minified = Attribute.of('minified', Boolean) configurations { compileElements { attributes.attribute(minified, false) } runtimeElements { attributes.attribute(minified, false) } }
此时内部项目的变体将带有minified=false属性,会被你的转换逻辑处理为true,自然满足解析要求。
关键说明
- 方法1是最直接的“排除”方案,通过修改解析策略让特定组件不受属性约束;
includeDependencies配置用于缩小转换范围,避免对不需要处理的库执行转换操作。
内容的提问来源于stack exchange,提问作者Nicholas Albion
相关产品推荐
相关产品推荐

