Frage

We have one and "only" one call to our injector...

Application app = injector.getInstance(Application.class);
app.start();

This has worked EXTREMELY well. Deep in the app though, we would like to have a certain Provider or something that creates a Class and more importantly wires his injections up as well. It may be something with AssistedInject but I am not 100% sure. We need something like the following

private Provider<SomeInterface> stuff;

public SomeInterface create(Class runtimeInst) {
  return stuff.get(runtimeInst);
}

Is there a way to do that at all?

War es hilfreich?

Lösung

As condit mentioned, if you look up the "default bindings" available on the Injector documentation, you'll see that an Injector can provide:

  • This Injector instance itself
  • A Provider<T> for each binding of type T
  • The java.util.logging.Logger for the class being injected
  • The Stage in which the Injector was created

This means that in any given class, if you've told Guice how to bind a T or Provider<T>, you can always @Inject either a T or Provider<T> and Guice will handle the wrapping or unwrapping through Provider as necessary.

In your particular case, it looks like you either need to specifically inject one of the following:

  • Provider<SomeInterface>, which returns whichever implementation you've bound SomeInterface to

  • Provider<SomeGuyImplementingSomeInterface>, which you can use to exactly specify exactly which SomeInterface implementor you need

  • @SomeAnnotation Provider<SomeInterface> (where you've bound @SomeAnnotation SomeInterface to the particular implementor SomeGuyImplementingSomeInterface in a module somewhere), if you want to be able to configure which non-default implementation to use all the way out at the Module level

  • Injector, if all else fails, and you absolutely need to get an instance from Guice based on a class literal kept a variable, so you can call injector.getInstance(clazz) directly. This will be the exact same Injector you used to create the topmost class, and will work exactly the same without you having to keep that Injector reference yourself. Try to avoid this solution unless you really need it; injecting only exactly what you need will make your testing easier and make your dependencies much more obvious.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top