如何在项目中兼容多版本Dagger依赖?
Great question! The short answer is yes, you can make these two versions coexist—but there are key configuration and code isolation rules you need to follow to avoid conflicts.
Core Reason They Can Coexist
Dagger 1 (maintained by Square, group ID com.squareup.dagger) and Dagger 2 (moved to Google, group ID com.google.dagger) evolved along separate paths, but Google provides a compatibility layer to let them run side-by-side. The main risk is class name collisions (e.g., both versions have a dagger.Module annotation), but the compat library solves this by bridging conflicting APIs.
Step-by-Step Setup
- Keep Component B's Dagger 1 dependencies: Retain your existing
com.squareup.dagger:dagger:1.2.1andcom.squareup.dagger:dagger-compiler:1.2.1for Component B's code. This will keep itsObjectGraph-based injection working exactly as before. - Add Dagger 2 dependencies with compatibility: For Library C, include these dependencies:
com.google.dagger:dagger:2.4(core Dagger 2 runtime)com.google.dagger:dagger-compiler:2.4(only needed if your project has its own Dagger 2 code to compile; skip if Library C is pre-compiled with generated components)com.google.dagger:dagger-compat:2.4(critical compatibility layer that resolves class conflicts between Dagger 1 and 2)
Critical Rules to Avoid Issues
- Isolate Dagger 1 and Dagger 2 code: Never mix annotations from both versions in the same class. For example, don’t use Dagger 1’s
@Modulealongside Dagger 2’s@Component—this will confuse both annotation processors and lead to compile failures. - Verify annotation processor behavior: Most build tools (Gradle, Maven) handle multiple annotation processors automatically, but double-check that Dagger 1’s compiler only processes Component B’s modules/injection points, while Dagger 2’s compiler handles Library C’s components.
- Don’t skip the compat layer: Without
dagger-compat, you’ll hit runtime errors likeNoClassDefFoundErrororClassCastExceptionbecause the classloader can’t resolve duplicate classes (e.g.,dagger.Modulefrom both versions). The compat layer is non-negotiable here.
Edge Case to Note
If Library C is a pre-built JAR that already includes its generated Dagger 2 components, you only need the Dagger 2 runtime (com.google.dagger:dagger:2.4) and dagger-compat:2.4—you don’t need the Dagger 2 compiler unless you’re writing new Dagger 2 code in your project.
内容的提问来源于stack exchange,提问作者Swastik Udupa

