依赖注入 – 匕首2 – @Singleton注释类的目的是什么

从匕首2 Documentation我注意到你可以有一个@Singleton注释类.将类标记为@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中,您可以通过模块OR或构造函数注入来提供注射.所以下列课程虽然不在模块中,但可以注入:

@Singleton
public class MyClass {

    @Inject
    public MyClass() {

    }
}

在这个版本中,构造函数是为我们注入的,在一个Android的活动中,你只需要执行以下操作即可:

@Inject
MyClass myClass;
//then in onCreate actually inject(this) from your graph of course.
@Singleton(和任何其他范围注释)使您的类成为依赖关系图中的单个实例(这意味着只要Component对象存在,此实例将为“singleton”).

总之,每次注入@Singleton注释类(使用@Inject注释)时,只要从同一个组件注入它,它将是同一个实例.

更多我指的是我的博客帖子关于@Singleton和其他范围注释在匕首2:http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/中的工作原理

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...