Dagger2: @Module为第三方库的构造函数提供注解

@Module 用法:当需要提供依赖的构造函数是第三方库而无法添加 @Inject 时,使用 @Module 提供注解。这个案例为了在依赖需求方 Car 类中不直接 new Engine(),而写了很多模板代码,看起来毫无意义。所以Dagger2大概只适合大型工程吧。

---
 .../me/li2/android/tutorial/Dagger2/Case1/Car.java  |  4 +++-
 .../tutorial/Dagger2/Case1/CarComponent.java        |  2 +-
 .../android/tutorial/Dagger2/Case1/CarModule.java   | 21 +++++++++++++++++++++
 .../li2/android/tutorial/Dagger2/Case1/Engine.java  |  4 +---
 4 files changed, 26 insertions(+), 5 deletions(-)
 create mode 100644 app/src/main/java/me/li2/android/tutorial/Dagger2/Case1/CarModule.java

diff Car.java

@@ -12,7 +12,9 @@ public class Car {
     Engine engine;

     public Car() {
-        DaggerCarComponent.builder().build().inject(this);
+        DaggerCarComponent.builder()
+                .carModule(new CarModule())
+                .build().inject(this);
     }

diff CarComponent.java

-@Component
+@Component(modules = {CarModule.class})
 public interface CarComponent {
     void inject(Car car);
 }


diff CarModule.java
new file mode 100644

/**
 * @Module and @Provides: define classes and methods which provide dependencies.
 * classes annotated with @Module are responsible for providing objects which can be injected. Such classes can define methods annotated with @Provides. The returned objects from these methods are available for dependency injection.
 * @Module用于标注提供依赖的类,@Provides用于标注Module所标注的类中的方法。当依赖提供方是第三方库时 无法加@Inject注解,或当构造函数带参数时无法通过@Inject提供参数,这种情况下需要 @Module 和 @Provides 注解。
 */

+import dagger.Module;
+import dagger.Provides;
+
+@Module
+public class CarModule {
+
+    public CarModule() {
+    }
+
+    @Provides
+    public Engine provideEngine() {
+        return new Engine();
+    }
+}

diff Engine.java

-import javax.inject.Inject;

 public class Engine {
-    @Inject
     public Engine() { 
     }