如何解决Android Studio中的重复类错误
解决Android Studio中的重复类依赖错误
错误详情
项目构建时触发重复类冲突,核心报错示例如下:
Duplicate class javax.annotation.CheckForNull found in modules jetified-annotations-3.0.1 (com.google.code.findbugs:annotations:3.0.1) and jetified-jsr305-3.0.2 (com.google.code.findbugs:jsr305:3.0.2) Duplicate class net.jcip.annotations.GuardedBy found in modules jetified-annotations-3.0.1 (com.google.code.findbugs:annotations:3.0.1) and jetified-jcip-annotations-1.0 (net.jcip:jcip-annotations:1.0) Duplicate class org.apache.commons.logging.Log found in modules jetified-commons-logging-1.2 (commons-logging:commons-logging:1.2) and jetified-spring-jcl-5.3.13 (org.springframework:spring-jcl:5.3.13)
其余冲突覆盖javax.annotation下的注解类、net.jcip.annotations线程安全注解类、org.apache.commons.logging日志实现类等,均为不同依赖包包含相同类定义导致。
修复方案
1. 排除冲突依赖
在Module级别的build.gradle中,为引发冲突的依赖添加排除规则,移除重复模块:
- 处理findbugs注解冲突:
dependencies { // 若直接引入annotations,排除其中的重复依赖 implementation('com.google.code.findbugs:annotations:3.0.1') { exclude group: 'com.google.code.findbugs', module: 'jsr305' exclude group: 'net.jcip', module: 'jcip-annotations' } // 若为间接依赖,找到引入冲突的库并排除重复模块 implementation('依赖组:依赖名:版本') { exclude group: 'com.google.code.findbugs', module: 'annotations' } }
- 处理日志依赖冲突:
dependencies { // 排除commons-logging,使用spring-jcl替代 implementation('org.springframework:spring-core:5.3.13') { exclude group: 'commons-logging', module: 'commons-logging' } }
2. 强制统一依赖版本
在项目根目录的build.gradle中,通过resolutionStrategy指定统一的依赖版本,确保冲突类仅来自指定包:
allprojects { configurations.all { // 统一findbugs相关依赖版本 resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.2' // 统一日志依赖为spring-jcl resolutionStrategy.force 'org.springframework:spring-jcl:5.3.13' } }
3. 替换为AndroidX注解(可选)
若项目已迁移至AndroidX,可移除findbugs相关依赖,改用AndroidX官方注解:
dependencies { implementation 'androidx.annotation:annotation:1.6.0' }
同时将代码中的javax.annotation.Nonnull等注解替换为androidx.annotation.NonNull等效注解。
内容的提问来源于stack exchange,提问作者Gata Miracle
相关产品推荐
相关产品推荐

