什么是maven存储库镜像的gradle等价物



在使用Maven项目时,我喜欢为各种第三方存储库配置本地镜像(例如Artifactory)。我通过主目录中的settings.xml文件来执行此操作。

我找不到类似的Gradle设置-所有文档似乎都建议添加一个新的存储库,而不是代理/镜像对已经定义的repo的调用。这并没有同样的效果。有没有一种简单的方法来代理Gradle中的远程Maven或Ivy存储库?

您可以定义自定义存储库,例如:

// build.gradle or settings.gradle
repositories {
  maven {
    url "http://repo1.mycompany.com/maven2"
  }
  maven {
    url "http://repo2.mycompany.com/maven2"
  }
}

如果您想在项目之间共享此定义,请将其移动到初始脚本

我们有一个内部的Artifactory存储库,它为库和插件、发布版本和快照版本配置了单独的路径。作为~/.m2/settings.xml的等价物,我使用了以下~/.gradle/init.gradle文件:-

allprojects {
    buildscript {
        repositories {
            mavenLocal()
            maven { url "https://internal.example.com/artifactory/libs-releases" }
            maven { url "https://internal.example.com/artifactory/libs-snapshots" }
            maven { url "https://internal.example.com/artifactory/atlassian-cache" }
        }
    }
    repositories {
        mavenLocal()
        maven { url "https://internal.example.com/artifactory/plugins-releases" }
        maven { url "https://internal.example.com/artifactory/plugins-snapshots" }
        maven { url "https://internal.example.com/artifactory/atlassian-cache" }
    }
}
  • CCD_ 4块指的是您的构建所使用的gradle插件的搜索位置
  • 第二个CCD_ 5块指的是搜索项目的依赖项的位置
  • mavenLocal()是指本地文件系统回购~/.m2/repository

更多信息:

  • https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies
  • https://docs.gradle.org/current/userguide/init_scripts.html

Gradle设置maven存储库镜像的最佳方法是修改init.Gradle或init.Gradle.kts.中的url

例如,我想将mavenCentral()镜像到'https://mirrors.tencent.com/nexus/repository/maven-public/'并将PluginPortal()分级为'https://mirrors.tencent.com/nexus/repository/gradle-plugins/',只需将代码放在<UserDir>/.gradle/init.gradle.kts:中即可

fun RepositoryHandler.enableMirror() {
    all {
        if (this is MavenArtifactRepository) {
            val originalUrl = this.url.toString().removeSuffix("/")
            urlMappings[originalUrl]?.let {
                logger.lifecycle("Repository[$url] is mirrored to $it")
                this.setUrl(it)
            }
        }
    }
}
val urlMappings = mapOf(
    "https://repo.maven.apache.org/maven2" to "https://mirrors.tencent.com/nexus/repository/maven-public/",
    "https://dl.google.com/dl/android/maven2" to "https://mirrors.tencent.com/nexus/repository/maven-public/",
    "https://plugins.gradle.org/m2" to "https://mirrors.tencent.com/nexus/repository/gradle-plugins/"
)
gradle.allprojects {
    buildscript {
        repositories.enableMirror()
    }
    repositories.enableMirror()
}
gradle.beforeSettings { 
    pluginManagement.repositories.enableMirror()
    dependencyResolutionManagement.repositories.enableMirror()
}

它将由您设备上的每个本地项目加载。不再修改项目的源代码。

最新更新