如何为匕首2创建模块

时间:2017-03-27 21:25:48

标签: java android dagger-2

我读过很多关于匕首2的文章,但我不明白如何为匕首2创建模块 可以说我有三个A,B,C三级 A取决于B和C. 我如何创建模块和组件

1 个答案:

答案 0 :(得分:0)

组件:

@Singleton
@Component(modules = {
        ApplicationModule.class
})
public interface ApplicationComponent {

    void inject(@NonNull A a);
}

模块:

@Module
public class ApplicationModule {
    @NonNull
    private final Application application;

    public ApplicationModule(@NonNull Application application) {
        this.application = application;
    }

    @Provides
    @NonNull
    @Singleton
    Application provideApp() {
        return application;
    }

    @Provides
    @NonNull
    @Singleton
    B provideB() {
        return new B();
    }

    @Provides
    @NonNull
    @Singleton
    C provideC() {
        return new C();
    }
}

您的应用程序类,使用模块初始化组件:

public class App extends Application {
    private ApplicationComponent applicationComponent;

    @NonNull
    public static App get(@NonNull Context context) {
        return (App) context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationComponent = prepareApplicationComponent().build();
    }

    @NonNull
    protected DaggerApplicationComponent.Builder prepareApplicationComponent() {
        return DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this));
    }

    @NonNull
    public ApplicationComponent applicationComponent() {
        return applicationComponent;
    }
}

你的A班(例如它的活动):

public class A extends AppCompatActivity {
    @Inject
    B b;
    @Inject
    C c;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        injectDependencies()
        setContentView(R.layout.activity_main);
        // working with b and c
    }

    private void injectDependencies() {
        App.get(this).applicationComponent().inject(this);
    }
}