Shailesh Jha
Shailesh Jha

Reputation: 11

Just in time binding in guice

Does just in time binding in guice injects the same instance again and again or does it create a new one on every injection. In other words does it maintain singleton by default or does it create new instances everytime ?

Upvotes: 1

Views: 1065

Answers (1)

Tomer Shetah
Tomer Shetah

Reputation: 8529

TL;DR: By default, Guice creates a new instance every time.

In order to test it, we can create a small program. Let's define an interface:

public interface SomeInterface {
    int getCounter();
}

And implementation:

class SomeInterfaceImpl implements SomeInterface {
   private static int counter = 0;

    @Inject
    public SomeInterfaceImpl() {
       counter++;
   }

    public int getCounter() {
        return counter;
    }
}

The main program will be:

public static void main(String[] args) {
    Injector injector = Guice.createInjector(binder -> {
        binder.bind(SomeInterface.class).to(SomeInterfaceImpl.class);
    });

    for (int i = 0; i < 3; i++) {
        SomeInterface impl = injector.getInstance(SomeInterface.class);
        System.out.println(impl.getCounter());
    }
}

The output of that program will be:

0
1
2

In order to have your class singleton you have 4 options:

  1. Define the class in a singleton class:

     Injector injector = Guice.createInjector(binder -> {
         binder.bind(SomeInterface.class).to(SomeInterfaceImpl.class).in(Singleton.class);
     });
    
  2. Define the class in a singlton scope:

     Injector injector = Guice.createInjector(binder -> {
         binder.bind(SomeInterface.class).to(SomeInterfaceImpl.class).in(Scopes.SINGLETON);
     });
    
  3. Define SomeInterfaceImpl as singleton:

    @Singleton
    class SomeInterfaceImpl implements SomeInterface {
    
  4. Call asEagerSingleton:

     Injector injector = Guice.createInjector(binder -> {
         binder.bind(SomeInterface.class).to(SomeInterfaceImpl.class).asEagerSingleton();
     });
    

To understand more about the differences between the 4 options, you can refer to the docs, or read Jeff's post about that.

Upvotes: 2

Related Questions