Introduction
This time I want to show you, what Guice will do, when we ask for provider for class, but we have not defined any provider and when we obtain new objects from injector and when already used objects. All sources are available here.Default providers
First, let's create a small class:public class UserSession {}We do not define any profider, but when we ask for provider, than provider will be given to us.
@Test public void shouldGetEachTimeNewSessionFromProvider(){ //given Injector injector = Guice.createInjector(); Provider<UserSession> sut = injector.getProvider(UserSession.class); //when UserSession userSession = sut.get(); //then assertNotNull(userSession); }
Scopes
For each request to injector or default provider we obtain new object. This is default scope of dependencies maintained by Guice. For example:
@Test public void shouldGetEachTimeNewSession(){ //given Injector sut = Guice.createInjector(); //when UserSession userSession1 = sut.getInstance(UserSession.class); UserSession userSession2 = sut.getInstance(UserSession.class); //then assertNotEquals(userSession1, userSession2); }
But suppose we should have only one instance of class, for example generator.
@Singleton public class SequenceGenerator { private int counter = 0; public int next(){ return counter++; } }
The Singleton annotation tells Guice that we want only one instance of this class, so if we get instance of this class from injector or default provider, than we obtain the same instance.
@Test public void shouldGetTheSameSequenceGeneratorEachTime(){ //given Injector injector = Guice.createInjector(); //when SequenceGenerator sequenceGenerator1 = injector.getInstance(SequenceGenerator.class); SequenceGenerator sequenceGenerator2 = injector.getInstance(SequenceGenerator.class); //then assertEquals(sequenceGenerator1, sequenceGenerator2); }
@Test public void shouldGetTheSameSequenceGeneratorEachTimeFromProvider(){ //given Injector injector = Guice.createInjector(); Provider<SequenceGenerator> sut = injector.getProvider(SequenceGenerator.class); //when SequenceGenerator sequenceGenerator1 = sut.get(); SequenceGenerator sequenceGenerator2 = sut.get(); //then assertEquals(sequenceGenerator1, sequenceGenerator2); }
Of course dependency is singleton in Guice context, so you could create new object of this class outside from Guice and no one could stop you.
Conclusion
Guice generates for us default providers in default scope. Providers give us new objects for each request to their. We could also change scope of class to Singleton and then for each request we obtain the same object.
No comments:
Post a Comment