I have a class Xyz which is injected into multiple classes. I use Guice for DI.
class Xyz{
static int i =0;
public Xyz(){
System.out.println("###########creating instance = " + (++i));
}
}
class ManagedOne{
Xyx xyz;
public ManagedOne(Xyz xyz){
this.xyz = xyz;
}
}
class ManagedTwo{
Xyx xyz;
public ManagedTwo(Xyz xyz){
this.xyz = xyz;
}
}
Guice
bind(Xyz.class).in(Singleton.class);
bind(ManageOne.class).in(Singleton.class);
bind(ManageTwo.class).in(Singleton.class);
- Now even if i remove the about binding i still see that Guice is creating singleton instance of Xyz. Verified using the sysout. It only prints it one with value 1. Is this the default behavior? I thought default was factory.
- Will Guice inject same instance of Xyz in both the managers? If yes, Is the code
bind(Xyz.class).in(Singleton.class)redundant then?
Note that i donot use injector.getInstance(Xyz.class) to get instance of Xyz all the time. Rather i do it the way i showed in my code above
Xyz: the first line you wrote isclass Xyz() {with()that shouldn't be here. So I guess you adapted your code shown. Also after I removed the(), I ran your code withvar injector = Guice.createInjector(); injector.getInstance(Xyz.class); injector.getInstance(Xyz.class); injector.getInstance(Xyz.class);and got the expected result###########creating instance = 1 ###########creating instance = 2 ###########creating instance = 3Therefore please provide a MCVE - Olivier Grégoire