Dagger2入门

1.@Conponent

@Component(modules = MainSurfaceViewModule.class)
public interface MainSurfaceViewComponent {
    void inject(MainSurfaceView mainSurfaceView);
}

2.@Module

@Module
public class MainSurfaceViewModule {

    public A a;

    public MainSurfaceViewModule(A a)
    {
        this.a = a;
    }

    @Qualifier
    @Documented
    @Retention(RUNTIME)
    public @interface Direction
    {
        String value() default "";
    }

    @Provides
    A provideA()
    {
        return a;
    }

    @Provides @Direction("MergeFront")
    B provideB()
    {
        return b;
    }
}

3.@Inject

public class B
{
    @Inject
    public B()
    {

    }
}

4.编译

Make Project 或者 Ctrl + F9 或者 Shift + Alt + X 或者 Ctrl + B

5.注入的类

public class MainSurfaceView
{  
    @Inject B b1;
    @Inject @MainSurfaceViewModule.Direction("MergeFront") B b2; 

    public MainSurfaceView()
    {
        DaggerMainSurfaceViewComponent.builder()
                .mainSurfaceViewModule(new MainSurfaceViewModule(a))
                .build().inject(this);
    }
}

你可能感兴趣的:(Dagger2入门)