匕首2中的模块中的@singleton和@singleton之间的差异



im学习dagger2,我注意到在某些示例中,模块的方法中有一个@Singleton,而在组件的方法上有其他@Singleton?有什么区别,在模块方法和组件方法上的@Singleton究竟是什么意思?

由于您是初学者,我强烈建议您尝试尝试。编写单元测试很容易,并且有助于理解和证明理论。

如果您还没有,请阅读用户指南以获取有关dagger和范围的一些基本知识。

注释方法组件(配置方法)中没有任何效果。您将必须在模块中注释类或提供方法。我想快速展示您如何快速证明自己:

我们有2个组件,一个使用范围@Singleton,另一个使用:

@Singleton
@Component(modules = SingletonModule.class)
public interface SingletonComponent {
    Object getObject();
}
@Component(modules = NormalModule.class)
public interface NormalComponent {
    @Singleton
    Object getObject();
}

使用这些组件有2个模块,一个模块提供了单元示波对象(与组件相同),另一个仅使用范围:

@Module
public class SingletonModule {
    @Provides
    @Singleton
    public Object provideObject() {
        return new Object();
    }
}
@Module
public class NormalModule {
    @Provides
    public Object provideObject() {
        return new Object();
    }
}

现在我们创建了一个小测试:

public class ComponentTest {
    @Test
    public void testSingletonComponent() {
        SingletonComponent component = DaggerSingletonComponent.create();
        Assert.assertEquals(component.getObject(), component.getObject());
    }

    @Test
    public void testNormalComponent() {
        NormalComponent component = DaggerNormalComponent.create();
        Assert.assertNotSame(component.getObject(), component.getObject());
    }
}

此测试将成功,并证明组件中的注释方法无能为力。使用构造函数注入时,模块中的范围对象或注释类本身会导致对象在同一范围/相同组件中重复使用

创建同一范围的2个组件也将导致重复的对象,因此可以证明这样的对象:

@Test
public void testTwoSingleonComponents() {
    SingletonComponent component1 = DaggerSingletonComponent.create();
    SingletonComponent component2 = DaggerSingletonComponent.create();
    Assert.assertNotSame(component1.getObject(), component2.getObject());
}

一定要阅读一些教程,并确保尝试一下。编译器 Will 如果您做错了事,请抱怨!:)

最新更新