If I have a module like this:
public class MyModule extends AbstractModule {
@Override
public void configure() {
bind(WhatsThis.class).to(AnAppleOfGold.class);
bind(TellMeYourName.class).to(Bosse.class);
}
@Provides
public AnAppleOfGold providesApple() {
return new AppleOfGold(providesFizz());
}
@Provides
public Bosse providesBosse() {
return new Bosse("Grab a hold of my beard", providesFizz());
}
@Provides @Singleton
public Fizz providesFizz() {
return new Fizz(Math.random());
}
}
Every time Guice uses providesApple and providesBosse to inject AnAppleOfGold and Bosse objects respectively, do they get the same singleton instance of Fizz? In other words, does Guice honor scope between provides methods, or does it only honor scope (in this case, Scopes.SINGLETON) from “outside” the module (the DI client code)? Thanks in advance.
Guice will honor Singleton scope between
@Providesmethods, providing that Guice is the one calling them.In your example, you call
providesFizz()manually, which works just like any other method call. Guice will inject a new instance each time you try to get a newAnAppleOfGoldorBosse. Meanwhile, it will create a separate new instance when you request aFizzthrough Guice, and return that same instance for everyFizzinjected through Guice.So how do you access the common instance from other
@Providesmethods? Simple: Guice will inject all parameters on your @Provides method, includingFizzorProvider<Fizz>.