1

对于Dagger2版本,我计划将模块拆分为几个小模块,以便在其他项目中重复使用。

应用模块包含很多东西,我可以将它分为三种类型。A型相关,B型相关,C型相关。

所以我想把它放到三个不同的模块中,因此如果需要其他项目,它可以重复使用其中的一部分。

来自Google's Fork 的参考资料

应用程序的 build.gradle

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.1.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        mavenCentral()
    }
}

应用程序模块的 build.gradle

apply plugin: 'com.neenbedankt.android-apt'
//below lines go to dependenc
compile 'com.google.dagger:dagger:2.0'
apt 'com.google.dagger:dagger-compiler:2.0'
provided 'org.glassfish:javax.annotation:10.0-b28'

完成上述步骤后,我将创建我的应用程序模块

@dagger.Module
public class MyApplicationModule {
  void inject(MyApplication application);
}

和我的组件

@Singleton
@Component(
        modules = {TypeA.class, TypeB.class, TypeC.class})
public interface MyApplicationComponent {

当我在活动中使用它时,它看起来像

@Component(dependencies = MyApplicationComponent.class,
        modules = ActivityModule.class)
public interface ActivityComponent {

    void injectActivity(SplashScreenActivity activity);

有编译问题

错误:(22, 10) 错误:没有 @Provides- 或 @Produces-annotated 方法无法提供 XXXXXX。com.myapplication.mXXX [注入的字段类型:XXX]

我想当我配置活动组件从应用程序组件扩展时有问题。

我的目的是 Application Component 中的一些单例对象,活动将注入相同的对象以减少每次在活动上创建的一些对象。我的设计错了吗??还是需要为配置做任何其他事情?

4

1 回答 1

1

找出根本原因来自@Scope

需要暴露类型以供其他子组件使用

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}

如果我们想公开应用程序的上下文,

@Singleton
@Component(
         {TypeA.class, TypeB.class, TypeC.class})
public interface MyApplicationComponent {

    void inject(MyApplication application);

    @ForApplication
    Context appContext();

当我的子组件想要扩展它时

@ActivityScope
@Component(dependencies = MyApplicationComponent.class,
        modules = ActivityModule.class)
public interface ActivityComponent extends MyApplicationComponent {

    void injectActivity(Activity activity);

我觉得这对于 Dagger2 来说是一件很棒的事情,让你手动暴露你需要使用的对象,代码变得更加可追溯。

于 2015-04-24T02:26:18.437 回答