Dagger 2 - what is the purpose of a @Singleton annotation class

后端 未结 5 867
既然无缘
既然无缘 2021-02-03 17:43

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 hav

5条回答
  •  一生所求
    2021-02-03 18:01

    @Singleton is inherit @Scope, so in documentation says

    Identifies scope annotations. A scope annotation applies to a class * containing an injectable constructor and governs how the injector reuses * instances of the type. By default, if no scope annotation is present, the * injector creates an instance (by injecting the type's constructor), uses * the instance for one injection, and then forgets it. If a scope annotation * is present, the injector may retain the instance for possible reuse in a * later injection. If multiple threads can access a scoped instance, its * implementation should be thread safe. The implementation of the scope * itself is left up to the injector.

    In the following example, the scope annotation {@code @Singleton} ensures * that we only have one Log instance: * *

     *   @Singleton
     *   class Log {
     *     void log(String message) { ... }
     *   }

    You get the point right? whatever annotation you use or you create a custom one, and they inherit from @Scope it will ensure as singleton.

提交回复
热议问题