Gradle 配置私有库

2,621 阅读2分钟

我们在工作中需要下载公有仓库里面的依赖包也需要下载公司私有仓库的依赖包,也需要发布自己编写的依赖到私有仓库供其他同事使用. 如果你使用gradle做Java依赖管理并遇到上述的问题,这篇文章可以帮到你

环境

下面是我的操作环境

软件版本
gradle7.3 +
javajdk17

打包

我们需要做到2件事

  • 指定源代码兼容版本,字节码兼容版本和字符编码;将项目编译为fatjar.
  • 附带打包一份对应的源代码
// -----------------------------------    gradle打包    ----------------------------------------------------------------

// 附带源代码
task sourceJar(type: Jar) {
    from sourceSets.main.allJava
    archiveClassifier = "sources"
}
// 编译
compileJava {
    // 源代码兼容版本
    sourceCompatibility = '17'
    // 字节码兼容版本
    targetCompatibility = '17'
    // 字符编码
    options.encoding = 'UTF-8'
}

// 打包
jar {
    // 打包时不附带plain.jar,只打包fatjar
    // https://stackoverflow.com/questions/67663728/spring-boot-2-5-0-generates-plain-jar-file-can-i-remove-it
    enabled = true
    //use empty string
    archiveClassifier = ''
}

设置私有仓库

我们需要做到2件事

  • 配置私有库,这样我们能从私有库下载自己需要的依赖
  • 配置私有库,在需要时我们可以上传自己打包的依赖到私有库,提供给其他人使用
// -----------------------------------NEXUS 包管理仓库设置----------------------------------------------------------------

// 从Nexus下载依赖
repositories {
    // 优先使用本地仓库
    mavenLocal()
    // 第二优先使用私有仓库
    maven {
        // 用户口令
        credentials {
            username 'your-username'
            password 'your-password'
        }
        // public仓库地址,包含release和snapshots
        url = "https://www.your-domain.com/repository/maven-public/"
    }
    // 最后使用私有仓库
    mavenCentral()
}

// 发布到Nexus私有库
publishing {
    publications {
        mavenJava(MavenPublication) {
            // 包含打包出的jar包
            from components.java
            // 包含源代码
            artifact sourceJar
        }
    }

    repositories {
        maven {
            // 用户口令
            credentials {
                username 'your-username'
                password 'your-password'
            }
            // release仓库地址
            def releasesRepoUrl = "https://www.your-domain.com/repository/maven-releases/"
            // snapshots仓库地址
            def snapshotsRepoUrl = "https://www.your-domain.com/repository/maven-snapshots/"
            // 根据版本信息动态判断发布到snapshots还是release仓库
            url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
            // 禁用使用非安全协议通信(比如http)
            allowInsecureProtocol false
        }
    }
}