Reputation: 11
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
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:
Define the class in a singleton class:
Injector injector = Guice.createInjector(binder -> {
binder.bind(SomeInterface.class).to(SomeInterfaceImpl.class).in(Singleton.class);
});
Define the class in a singlton scope:
Injector injector = Guice.createInjector(binder -> {
binder.bind(SomeInterface.class).to(SomeInterfaceImpl.class).in(Scopes.SINGLETON);
});
Define SomeInterfaceImpl
as singleton:
@Singleton
class SomeInterfaceImpl implements SomeInterface {
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