使用 repositoryContentFiltering 阻止快照包流入 release 仓库的完整配置?
解读
在国内金融、电商、运营商等对“制品可信”要求极高的场景里,release 仓库一旦混入快照包就可能导致线上事故。Gradle 6.8+ 提供的 repositoryContentFiltering 是官方推荐的“仓库级防火墙”,它能在依赖解析阶段就把快照挡在门外,而不是等到上传阶段才做二次校验。面试官问“完整配置”,其实想看三点:
- 是否知道release 仓库与 snapshot 仓库必须物理隔离(国内 Nexus/Artifactory 私服双库模式);
- 能否写出同时拦截 group、version、snapshot 后缀的严谨规则;
- 是否理解
repositoryContentFiltering与resolutionStrategy的职责边界:前者是“不让它进来”,后者是“进来后怎么选版本”,两者互补,不能互相替代。
知识点
- repositoryContentFiltering 只在
repositories{}块内生效,优先于依赖解析,性能最好。 - 拦截快照的核心是
!version.contains("-SNAPSHOT")的Groovy/Kotlin 谓词表达式;同时建议按 group 前缀白名单放行,防止误杀第三方 release 包。 - 国内私服通常把 release 仓库 URL 指向
https://nexus.xxx.com/repository/maven-releases/,snapshot 仓库指向同级 maven-snapshots/,两库禁止混用同一 URL,否则过滤规则形同虚设。 - 若项目使用
dependencyLocking或catalogs,过滤规则仍需显式声明,不会自动继承。 - CI 阶段要配合
./gradlew build --refresh-dependencies做负向测试:故意把-SNAPSHOT写进依赖,构建失败才证明过滤生效。
答案
以下示例基于 Kotlin DSL,直接复制即可通过国内 Nexus 私服验收:
// rootProject/build.gradle.kts
repositories {
maven {
name = "NexusRelease"
url = uri("https://nexus.xxx.com/repository/maven-releases/")
credentials {
username = findProperty("nexus.user") as String?
password = findProperty("nexus.password") as String?
}
// 关键:阻止任何快照包进入 release 仓库
mavenContent {
// 只允许 release 版本
releasesOnly()
// 二次兜底:自定义过滤
excludeGroupByRegex(".*-SNAPSHOT")
excludeVersionByRegex(".*-SNAPSHOT")
}
}
// snapshot 仓库完全独立
maven {
name = "NexusSnapshot"
url = uri("https://nexus.xxx.com/repository/maven-snapshots/")
credentials {
username = findProperty("nexus.user") as String?
password = findProperty("nexus.password") as String?
}
mavenContent {
snapshotsOnly()
}
}
// 中央仓库作为只读兜底
mavenCentral {
mavenContent {
// 只允许 release,防止中央快照污染
releasesOnly()
}
}
}
// 强制校验:若解析到快照直接抛异常
configurations.all {
resolutionStrategy {
failOnVersionConflict()
// 兜底二次校验,性能损耗可忽略
eachDependency {
if (requested.version.orEmpty().endsWith("-SNAPSHOT")) {
throw GradleException("Snapshot dependency ${requested.group}:${requested.name}:${requested.version} is not allowed in release build!")
}
}
}
}
验证步骤(面试时可口述):
- 本地
~/.gradle/gradle.properties中故意写错一个快照版本; - 执行
./gradlew build --refresh-dependencies,构建必须失败并提示被repositoryContentFiltering拦截; - 在 CI 的
Jenkinsfile里加一条负向测试 stage,快照依赖被拦截后流水线才继续,国内银行项目普遍要求此用例通过才给投产单。
拓展思考
- 多项目构建:在
buildSrc或included builds里单独声明 repositories,否则子项目可能绕过过滤规则; - 复合过滤:国内有些包版本号不带
-SNAPSHOT但时间戳后缀(如1.0.0-20230601.020455-1),需要excludeVersionByRegex(".*-\\d{8}\\.\\d{6}-\\d+")才能彻底拦截; - 远程构建缓存:开启
org.gradle.caching=true后,过滤规则变更不会自动使缓存失效,需在 CI 上手动rm -rf $GRADLE_USER_HOME/caches或提升缓存 key; - 未来演进:Gradle 8.5 将引入
repository content filter的共享插件,届时可把上述逻辑封装成公司级settings-conventions插件,一行id("com.xxx.repo-filter")即可全仓库生效,面试时可作为“对社区动向保持关注”的加分项。