IAmYourFaja
IAmYourFaja

Reputation: 56874

Do Guice provider methods honor scope?

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.

Upvotes: 2

Views: 1861

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95614

Guice will honor Singleton scope between @Provides methods, 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 new AnAppleOfGold or Bosse. Meanwhile, it will create a separate new instance when you request a Fizz through Guice, and return that same instance for every Fizz injected through Guice.

So how do you access the common instance from other @Provides methods? Simple: Guice will inject all parameters on your @Provides method, including Fizz or Provider<Fizz>.

@Provides
public AnAppleOfGold providesApple(Fizz fizz) {
  return new AppleOfGold(fizz);
}

@Provides
public Bosse providesBosse(Provider<Fizz> fizzProvider) {
  return new Bosse("Grab a hold of my beard", fizzProvider.get());
}

@Provides @Singleton
public Fizz providesFizz() {
  return new Fizz(Math.random());
}

Upvotes: 5

Related Questions