在开发过程中,随着项目扩大,经验累积,会产生出来一些类似 SDK 的代码库,如果是个人的代码库,可以放在 maven 的远程仓库上,如果不想公开,则可以搭建一个私有的仓库。

本文重点在于记录使用 nexus 搭建私有的 Android 仓库的过程。

安装 nexus

下载 nexus

安装之后执行对应的可执行文件即可。

安装过程中需要指定程序占内存的大小,如果内存设置过大,会出现服务跑不起来的情况。

建立一个仓库

在 web 管理界面 http://ip:port 新建一个 maven2(hosted) 的仓库

IP 一般是 localhost,当然远程的话,就是远程服务器的 IP,实际上,IP 为远程 IP 才会显得比较有意义。
port 一般是默认的 8081

使用 Android Studio 上传代码库

编辑 lib module 的 build.gradle 的文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
apply plugin: 'maven'

uploadArchives {
repositories {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def RELEASE_REPOSITORY_URL = properties.getProperty('RELEASE_REPOSITORY_URL')
def nexusUsername = properties.getProperty('nexusUsername')
def nexusPassword = properties.getProperty('nexusPassword')
mavenDeployer {
repository(url: RELEASE_REPOSITORY_URL) {
authentication(userName: nexusUsername, password: nexusPassword)
}

pom.project {
name PROJ_GROUP_ID
packaging POM_PACKAGING
groupId PROJ_GROUP_ID
artifactId PROJ_ARTIFACT
version PKG_VERSION
}
}
}
}

在项目的根目录,编辑 gradle.properties 文件

1
2
3
4
PKG_VERSION=1.0.0
PROJ_GROUP_ID=repoName
PROJ_ARTIFACT=libId
POM_PACKAGING=aar

敏感信息放在版本控制之外的 local.properties

1
2
3
nexusUsername=username
nexusPassword=password
RELEASE_REPOSITORY_URL=http://ip:port/repository/repoName/

对照表

key desc
nexusUsername 即 web 管理界面的用户名
nexusPassword 即 web 管理界面的密码
RELEASE_REPOSITORY_URL 仓库的 URL
PKG_VERSION 版本号
PROJ_GROUP_ID 仓库名称
PROJ_ARTIFACT 组件 ID (一个仓库可以有多个组件)
POM_PACKAGING 打包方式

在 bash 中执行 gradle 的任务

每一次 upload,gradle文件中的 version 的值都需要改变

1
gradle uploadArchives

在项目中对该仓库进行依赖

app-level 的 build.gradle:

1
2
3
4
5
6
7
8
9
10
allprojects {
repositories {
jcenter()


maven {
url 'RELEASE_REPOSITORY_URL'
}
}
}

module-level 的 build.gradle:

1
2
3
dependencies {
compile 'groupID:ArtifactID:versionCode'
}