Guice Tutorial - 09 - Providers in modules


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


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 {
    protected void configure() {}

    private Quiz getinitializedQuiz(){
        Quiz quiz = new Quiz();
        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:
public void shouldClassInstanceFromProvider(){
    Injector sut = Guice.createInjector(new QuizModule());
    Quiz quiz = sut.getInstance(Quiz.class);


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