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

j2emanue picture j2emanue · Jun 28, 2015 · Viewed 45.8k times · Source

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:

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 {
    // ...
}

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() {

    }
}

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.

Answer

froger_mcs picture froger_mcs · Jul 2, 2015

@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).

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.

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/