【问题标题】:Problems with singletons when using component dependencies使用组件依赖时的单例问题
【发布时间】:2015-01-27 12:13:54
【问题描述】:

我无法理解为什么以下代码不起作用。

我有以下项目结构:

@Component(modules = CCModule.class) 
public interface CComponent {
    XXX getXXX();
}

在哪里

@Module
public class CCModule {

    @Provides @Singleton
    public XXX provide XXX(){
        return new XXX();
    }
}

@Component(dependencies = CComponent.class, modules = AAModule.class) 
public interface AComponent {
    YYY getYYY();
}

在哪里

class YYY {
   @Inject
   public YYY(XXX xxx) {
       ...
   }
}

我将所有内容初始化为:

CComponent c_component = Dagger_CComponent.builder().cCModule(new CCModule()).build();

AComponent a_component = Dagger_AComponent.builder()
        .cComponent(c_component)
        .aAModule(new AAModule())
        .build();

编译后出现以下错误:

错误:(11, 1) 错误: com.test.CComponent (unscoped) 可能不会 参考范围绑定:@Provides @Singleton com.test.XXX com.test.CCModule.provideXXX()

我的目标是让一个组件从其他组件继承绑定以对对象(单例)具有相同的引用。

【问题讨论】:

    标签: java dagger-2


    【解决方案1】:

    你应该把@Singleton放到CComponent类声明中。

    @Singleton
    @Component(modules = CCModule.class) 
    public interface CComponent {
        XXX getXXX();
    }
    

    解释在错误消息中:CComponent 是无范围的,@Singleton 是一个范围。 Dagger 2 不允许非作用域组件使用具有作用域绑定的模块。
    但是,现在您将收到以下错误:

    AComponent (unscoped) cannot depend on scoped components:
    @Component(dependencies = CComponent.class, modules = AModule.class)
    

    无作用域的组件不能有作用域的依赖项。所以你需要使AComponent 作用域。为此,请创建自定义 AScope 注释。

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

    并用它注释AComponent:

    @AScope
    @Component(dependencies = CComponent.class, modules = AModule.class)
    public interface AComponent {
    }
    

    这些是最新snapshot release 中出现的新要求。已在相应的issue 中讨论过,可能仍会更改。

    【讨论】:

    • @AlexanderVasiljev 在最新快照上测试。工作正常=)。使用自定义 AScope 注释更新了我的答案。你的代码有问题。展示下。顺便说一句,我们用英语说话,这不是俄语资源。
    • 清洁解决方案先生
    【解决方案2】:

    添加

    @Singleton
    @Component(modules = {NameModule.class})
    public interface NameComponent {
    
    }
    

    对于组件,因为 dagger2 不允许将无作用域组件与作用域模块一起使用

    【讨论】:

      【解决方案3】:

      看起来像是最新的 Dagger-2 版本中的一个错误: https://github.com/google/dagger/issues/107

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多