通过Maven发布依赖AAR的Android自定义库遇依赖解析失败问题
解决自定义Android库发布Maven后无法包含依赖AAR的问题
问题根源
本地测试正常是因为embed或api能直接引用本地项目,但发布Maven时,默认的components.release不会将依赖的AAR打包进产物,且pom文件会保留对:separate_file的依赖声明——而该项目未发布到Maven仓库,最终导致依赖解析失败。
方案1:使用fat-aar插件正确打包并发布(推荐)
步骤1:配置fat-aar插件
在项目根目录build.gradle中保留插件依赖:
buildscript { dependencies { classpath 'com.github.kezong:fat-aar:1.3.8' } }
在自定义库的build.gradle中应用插件:
apply plugin: 'com.kezong.fat-aar'
步骤2:用embed引入依赖的AAR项目
替换原来的api project(':separate_file')为:
embed project(':separate_file')
步骤3:修改Maven发布配置
调整发布逻辑,直接使用fat-aar生成的合并后的AAR作为发布产物,并清理pom中的无效依赖:
project.afterEvaluate { def groupId = 'com.ss' def artifactId ='mylib' def versionName = '1.0.0' publishing { publications { MyLibrary(MavenPublication) { // 指定fat-aar生成的release AAR文件 artifact("$buildDir/outputs/aar/${artifactId}-release.aar") { extension 'aar' } // 移除pom中对separate_file的依赖声明 pom.withXml { def dependencies = asNode().get('dependencies') if (dependencies) { asNode().remove(dependencies) } } setGroupId groupId setArtifactId artifactId version versionName } } repositories { maven { url "artifacts" } } } }
步骤4:执行发布命令
运行Gradle任务完成发布:
./gradlew clean publish
方案2:直接将AAR文件打包进自定义库(无需separate_file)
如果不想依赖fat-aar插件,可以直接处理本地AAR文件:
- 将
myaar.aar放到自定义库的libs目录下。 - 在自定义库的
build.gradle中添加依赖和资源合并逻辑:
android { sourceSets { release { // 合并AAR中的资源文件 res.srcDirs += zipTree('libs/myaar.aar').matching { include 'res/**' }.files // 合并AAR中的Manifest(按需添加) manifest.srcFile zipTree('libs/myaar.aar').matching { include 'AndroidManifest.xml' }.singleFile } } } dependencies { // 引入AAR并合并类文件 implementation files('libs/myaar.aar') } // 发布时清理pom中的本地依赖声明 publishing { publications { MyLibrary(MavenPublication) { from components.release setGroupId 'com.ss' setArtifactId 'mylib' version '1.0.0' pom.withXml { def dependencies = asNode().get('dependencies') if (dependencies) { asNode().remove(dependencies) } } } } repositories { maven { url "artifacts" } } }
内容的提问来源于stack exchange,提问作者abhishek maharajpet
相关产品推荐
相关产品推荐

