Injector is injectable in your graph, and Guice will supply arguments to @Provides
methods. However, you should only ever need to inject your Injector in very rare cases, and there is no need to request an Injector if you don't use it.
@Provides
public Foo getFoo(Dep1 dep1, Dep2 dep2) {
return new Foo(dep1, dep2);
}
This assumes Guice can create instances of Dep1 and Dep2 (via constructors, bindings, or @Provides
methods), and is roughly equivalent to if you had annotated a constructor in Foo. Guice will inject instances of Dep1 and Dep2 when calling the Foo constructor, and Guice will provide the instances when calling your @Provides Foo getFoo
method above.
@Inject public Foo(Dep1 dep1, Dep2 dep2) { /* ... */ }
As in the documentation for the Injector class that you linked (latest docs available here):
Contains several default bindings:
- This
Injector
instance itself
- A
Provider<T>
for each binding of type T
- The
Logger
for the class being injected
- The
Stage
in which the Injector was created
Consequently, you may put Dep1, Dep2, Provider, Provider, Injector, or Provider<Injector>
into your @Provides
method arguments or @Inject
constructor arguments (or @Inject
fields, etc). Internally, Injector support happens in InjectorShell.java
as a special case, because parent and child Injectors will return different instances of Injector as an exception to Guice's rules about parents and children with the same bindings.
Why would you want to inject an Injector? For the sake of reading and testing, it is usually better to inject the dependency you need (e.g. Dep1) or its provider (e.g. Provider<Dep1>
). You would only need to inject the Injector if you need to pass it into some other object, like a legacy Service Locator that you've adapted to use your Guice Injector, or if you need to use the Injector reflectively via Guice's SPI or to get an instance based on a Class object. These are rare, and not likely to be necessary in most of your classes or @Provides
methods.
/** Exceptions, generics, and casting omitted for readability. */
@Provides SomeInterface getSomeInterface(
MyAppPreferences preferences,
Injector injector) {
Class<?> clazz = Class.forName(preferences.getSomeInterfaceImplName());
return injector.getInstance(clazz);
}
See also: Accessing Guice injector in its Module?