Dagger2: @Inject标记需要依赖的变量和提供依赖的构造器,@Component建立彼此的联系,最后调用@Component的生成类来完成注入

@Component is used on an interface. Such an interface is used by Dagger 2 to generate code. The base pattern for the generated class is that Dagger is used as prefix followed by the interface name. It defines the connection between provider of objects (modules) and the objects which expresses a dependency.

@Component用于标注接口,是依赖需求方和依赖提供方之间的桥梁。被Component标注的接口在编译时会生成该接口的实现类(生成的类名=接口名加前缀Dagger),通过调用这个实现类的方法完成注入。

import dagger.Component;

+@Component
+public interface CarComponent {
+    void inject(Car car);
+}

Use @Inject to annotate the constructor that Dagger should use to create instances of a class, to fulfill/provide dependencies. When a new instance is requested, Dagger will obtain the required parameters values and invoke this constructor.

@Inject 作用之一是用来标记构造函数。当需要该类的实例时,Dagger2会获取该构造函数的参数并调用它以构造一个实例,为被@Inject标记的变量提供依赖。

import javax.inject.Inject;

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

    public void run() {
        System.out.println("Engine is running");
    }
}

@Inject annotation can be used on a field to define a dependency. @Inject 作用之二是标记需要依赖的变量,以此告诉Dagger2为它提供依赖。

import javax.inject.Inject;

public class Car {
+    @Inject
    Engine engine;

    public Car() {
+        // 调用 @Component 的生成类来完成注入
+        DaggerCarComponent.builder().build().inject(this);
    }

    public Engine getEngine() {
        return this.engine;
    }
}

Test:

import org.junit.Test;

public class Case1Test {
    @Test
    public void test(){
        Car car = new Car();
        // 如果没有调用 DaggerCarComponent.builder().build().inject(this) 完成注入,
        // 则依赖的提供和需求方不会建立联系,car为null
        car.getEngine().run();
    }
}