I am extending Guice's AbstractModule
and inside of the extending class I need access to Guice's injector. It that possible, if yes, how?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
This is an unusual request. Modules are more like config files than logic files: The Module is read to create the Injector, and then as soon as the Injector is created the module has done its job. For a simple Module, the Injector literally doesn't exist until the Module is ready to be discarded.
In any case, rather than requesting an Injector to get class X, you should typically request a
Provider<X>
. Guice will inject anX
orProvider<X>
for any binding ofX
,Provider<X>
, or@Provides X
, so you can almost always do this instead. That said, injecting the Injector will allow you to get an instance reflectively, or to inspect the Injector's bindings (etc).Here are a few valid reasons/designs that would require accessing an Injector from within a Module:
In a
@Provides
method:Modules can contain mini-providers in methods annotated with
@Provides
. Remember thatInjector
is injectable: If you need an Injector in one of those methods, you can just accept it as a parameter:To get a Provider in your configure():
AbstractModules expose
getProvider()
for exactly this reason, though you'll get an error if you callget()
on that Provider before the injector is ready to provide it (such as at configuration time):You can probably call
getProvider(Injector.class)
but I don't know whether that works and I don't know why you'd want to.To get an instance in your configure():
This is a bad idea; Guice is not ready to provide instances until after all of the configure methods run. The closest you can get is to create a child Injector using the other modules and pass it into this module, but even that is rarely needed.