Scopes in Google Guice
Most of the scopes we have seen for the Spring Framework similarly exist in Google Guice. Scope defines that code should work in a specific context, and in Guice, the Injector manages the scope context. Default scope (No Scope), singleton, session, and request are the main scopes in Guice.
Default scope
By default, Guice injects a new and separate instance of an object for each dependency (similar to the prototype scope in Spring), whereas Spring provides singletons by default.
Let us consider an example of a house that has a family with three people, all with their own personal car. Every time they call the injector.getInstance()
method, a new instance of a car object is available for each family member:
home.give("Krunal", injector.getInstance(Car.class)); home.give("Jigna", injector.getInstance(Car.class)); home.give("Dirgh", injector.getInstance(Car.class));
Singleton scope
If we want to create only one instance of the class, then the @Singleton
annotation can be...