Here's something weird. Suppose you have a module like this:
public class ParentModule extends AbstractModule {
@Override
public void configure() {
bindConstant().annotatedWith(Names.named("key")).to("key");
}
}
Then we also have something like this:
public class DependentModule extends AbstractModule {
private final String key;
@Inject public DependentModule(@Named("key") String key) { this.key = key; }
@Override
public void configure() {
// Configure bindings that make use of key...
}
}
Injector parent = Guice.createInjector(new ParentModule());
Injector child = parent.createChildInjector(parent.getInstance(DependentModule.class));
// Now just ignore parent and work with child exclusively
This seems extremely cumbersome, but possibly necessary and useful in certain situations (if the key is a more complex datatype, for instance). Regardless, is there a way to restructure this code such that ParentModule
binds the key, creates the DependentModule
using the key, and install the created DependentModule
? That is, such that the consumer can simply use a single injector instead of having to do this two-injector trick?