使用组件依赖时单例的问题 [英] Problems with singletons when using component dependencies

查看:306
本文介绍了使用组件依赖时单例的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解为什么以下代码不起作用时遇到了问题。

I'm having a problem in understanding why the following code doesn't work.

我有以下项目结构:

@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) {
       ...
   }
}

我将所有内容初始化为:

I initialize everything as:

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

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

编译完成后,我收到以下错误:

Once compilation takes place i get the following error:

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

Error:(11, 1) error: com.test.CComponent (unscoped) may not reference scoped bindings: @Provides @Singleton com.test.XXX com.test.CCModule.provideXXX()

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

What I'm aiming for is to have one component inherit bindings from other components to have the same references to an objects (singletons).

推荐答案

你应该放 @Singleton CComponent 类声明。

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

说明错误消息: CComponent 是无范围的, @Singleton 是范围。 Dagger 2不允许未范围内的组件使用带范围绑定的模块。

但是,现在您将收到以下错误:

Explanation is in error message: CComponent is unscoped, @Singleton is a scope. Dagger 2 does not allow unscoped components to use modules with scoped bindings.
However, now you will get the following error:

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

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

Unscoped components cannot have scoped dependencies. So you need to make AComponent scoped. To do this create custom AScope annotation.

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

并用它注释 AComponent

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

这些是最新快照发布中出现的新要求。相应的问题对此进行了讨论,可能仍会进行更改。

These are new requirements appeared in latest snapshot release. It was discussed in corresponding issue and may still be changed.

这篇关于使用组件依赖时单例的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆