Dagger2 Singleton 注解

Dagger2学习过程中一直以为被 @single注解会有类似static效果(效果相同只是实现方式并不是static,下面会提到双重检查锁)。无意找到如下说明

@Singleton
means there will be one instance of the object for the lifetime of the component, not for the lifetime of the JVM.
and
Adding a scope annotation to a @Provides
method means that the method will be called at most once within one instance of the component it's installed into. Without that, the @Provides
method would be called again every time a Provider
's get()
method is called, even within one component instance. Every class that @Injects
a RestRepository
would get a new instance

@single dagger2会在生成的DaggerxxComponent文件的初始化方法中以 ScopedProvider 包裹提供依赖:

DaggerxxComponent.java

private void initialize(final Builder builder) { 

 this.providesAnimProvider = ScopedProvider.create(AnimModule_ProvidesAnimFactory.create(builder.animModule));

 }

ScopeProvider.java 单例模式 - 双重检查锁模式

 public T get() {
 // double-check idiom from EJ2: Item 71
 Object result = instance;
 if (result == UNINITIALIZED) {
 synchronized (this) {
 result = instance;
 if (result == UNINITIALIZED) {
 instance = result = factory.get();
 }
 }
 }
 return (T) result;
 }

Adding a scope annotation to a @Providesmethod means that the method will be called at most once within one instance of the component it's installed into.
达到以上效果是通过ScopeProvider的get方法控制的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,496评论 0 23
  • 《卫风 氓》之中有两句很有意思的话 于嗟鸠兮,无食桑葚 为什么?为什么不要斑鸠贪吃桑葚呢? 哈哈,就是啊,奇怪着呢...
    MsDiva阅读 3,783评论 0 1
  • 刚才看到了这个话题 就想写写 是在菜市场买菜的时候还要斤斤计较吧 买一件六七十块钱的衣服都觉得心疼 一根雪糕三块钱...
    不想让人知道我阅读 1,360评论 0 0
  • 简介 MooseFS 是一个分布式文件系统,支持以客户端挂载的形式开放给用户使用。 主要角色 master 节点:...
    Jeffbond阅读 8,131评论 0 0
  • 某哥:最近金砖会议,按摩都查得严。就在海沧,各种盲人按摩,都不让按了。我找了满大街。。。 我:找了满大街,都没人肯...
    聊点正事儿阅读 3,437评论 0 1

友情链接更多精彩内容