发布Library到Local Maven时如何包含嵌套依赖库?
问题:发布带子依赖的Library到Local Maven后,下游项目找不到子依赖类
我有一个包含其他子依赖库的Library A,用以下代码将其发布到Local Maven:
project.afterEvaluate { publishing { publications { // Creates a Maven publication called "release". release(MavenPublication) { // Applies the component for the release build variant. // You can then customize attributes of the publication as shown below. groupId = 'com.example.MyLibrary' artifactId = 'final' version = '1.3.8' artifact(sourceJar) artifact bundleReleaseAar } } } }
但在其他项目引入该库后,调用Library A中子依赖库的类时应用崩溃,报错:
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/studyo/code/CodingViewModel;
其中com/studyo/code是子依赖库的路径。
原因分析
当前的发布配置只上传了Library A的AAR包和源码包,但没有把Library A的依赖关系写入Maven的POM文件。下游项目引入Library A时,无法自动拉取它依赖的子库,导致运行时找不到子库的类。
解决方法
方法1:关联Release组件(推荐)
修改发布配置,用from components.release自动关联组件的所有信息(包括依赖、AAR包等),Gradle会自动生成包含依赖的POM文件:
project.afterEvaluate { publishing { publications { release(MavenPublication) { // 关联release组件,自动包含依赖、AAR等元信息 from components.release groupId = 'com.example.MyLibrary' artifactId = 'final' version = '1.3.8' artifact(sourceJar) // 保留源码包的上传 } } } }
重新发布后,下游项目引入Library A时会自动拉取所需的子依赖。
方法2:手动配置POM依赖
如果需要手动控制POM中的依赖项,可以添加pom.withXml节点手动注入子依赖的坐标:
project.afterEvaluate { publishing { publications { release(MavenPublication) { groupId = 'com.example.MyLibrary' artifactId = 'final' version = '1.3.8' artifact(sourceJar) artifact bundleReleaseAar // 手动添加子依赖到POM文件 pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') // 替换为子依赖库的真实坐标 def depNode = dependenciesNode.appendNode('dependency') depNode.appendNode('groupId', 'com.studyo') depNode.appendNode('artifactId', 'code') depNode.appendNode('version', 'x.y.z') // 子依赖的实际版本号 depNode.appendNode('scope', 'compile') } } } } }
注意替换代码中的x.y.z为子依赖库的真实版本号。
内容的提问来源于stack exchange,提问作者Ifan 767
相关产品推荐
相关产品推荐

