2014-05-17

Guice Tutorial - 09 - Providers in modules

Introduction

Module in Guice is not only a place where binding are defined. It also could have definition of many providers inside.


Provides

Suppose we have quiz class which has to be initialized before usage by call of method init.
public class Quiz {
    private boolean initialized = false;

    public boolean initialized(){
        return initialized;
    }

    public void init(){
        initialized = true;
    }
}
Provider is quite simple, because it only creates Quiz object and call method init, so we define it inside module.
public class QuizModule extends AbstractModule {
    @Override
    protected void configure() {}

    @Provides
    private Quiz getinitializedQuiz(){
        Quiz quiz = new Quiz();
        quiz.init();
        return quiz;
    }
}
Provides annotation tells Guice that annotated method is provider for its return type. Provider could be defined in this manner only in module.
Let's test it:
@Test
public void shouldClassInstanceFromProvider(){
    //given
    Injector sut = Guice.createInjector(new QuizModule());
    //when
    Quiz quiz = sut.getInstance(Quiz.class);
    //then
    assertTrue(quiz.initialized());
}

Conclusion

If you have to define provider, but you do not want to have separete provider class, than you could create method which acts like provider in your module. Sources are available here.

No comments:

Post a Comment