Dagger 2-@Singleton注释类的目的是什么 [英] Dagger 2 - what is the purpose of a @Singleton annotation class
问题描述
在匕首2中文档我注意到您可以拥有 @Singleton
带注释的类。我试图在代码中将类标记为 @Singleton
的目的是什么,但未生成单例对象。我尚不清楚使用此注释标记班级的用途。
From the dagger 2 Documentation I noticed that you can have a @Singleton
annotated class. What is the purpose of marking a class as @Singleton
as I have tried to do this in my code but a singleton object is NOT produced. I'm not clear on what use marking my class with this annotation serves.
在文档中,请重点关注以下语句:
From the documentation please focus on the following statement:
@Singleton注射类的注解也可用作
文档。它提醒潜在的维护者,此类可能是由多个线程共享的
。*
The @Singleton annotation on an injectable class also serves as documentation. It reminds potential maintainers that this class may be shared by multiple threads.*
@Singleton
class CoffeeMaker {
// ...
}
更新:查看froger_mcs答案后,我看到在Dagger 2中,您可以通过模块或构造函数注入来提供注入。因此可以注入以下类,尽管不在模块中:
UPDATE: After reviewing froger_mcs answer I see that in Dagger 2 you can provide injections either by a module OR by a constructor injection. So the following class, although not in a module, can be injected:
@Singleton
public class MyClass {
@Inject
public MyClass() {
}
}
在此版本中,为我们注入了构造函数,并且在Android活动中,您只需执行以下操作即可得到它:
In this version the constructor is injected for us and in an Android activity you would just do the following and it will get provided:
@Inject
MyClass myClass;
//then in onCreate actually inject(this) from your graph of course.
推荐答案
@Singleton
(以及任何其他作用域注释)使您的类成为依赖关系图中的单个实例(这意味着只要Component对象存在,此实例将是单个)。
@Singleton
(and any other scope annotation) makes your class a single instance in your dependencies graph (it means that this instance will be "singleton" as long as Component object exists).
简而言之-每次注入 @Singleton
带注释的类(带有 @Inject
注释),只要您从相同的组件注入它,它将是相同的实例。
In short - everytime you're injecting @Singleton
annotated class (with @Inject
annotation) it will be the same instance as long as you inject it from the same Component.
有关更多信息,我指的是我的博客文章关于 @Singleton
和其他作用域注释在Dagger 2中的工作方式: http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/
For more I'm referring my blog post about how @Singleton
and other scopes annotations works in Dagger 2: http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/
这篇关于Dagger 2-@Singleton注释类的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!