0

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?

1
  • 1
    It is not at all clear what you're asking. Consider writing a SSCCE that illustrates what your code is supposed to do.
    – The111
    Commented Dec 17, 2014 at 5:19

1 Answer 1

3

It isn't possible to inject something and then install it. Injection only happens after all your configure() methods have run, by which point it's too late. But you can do this:

public class MyModule extends AbstractModule {
    @Override
    public void configure() {
        bindConstant().annotatedWith(Names.named("key")).to("key");
    }

    @Provides
    Dependency provideDependency(@Named("key") String key) {
        // Use key here
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.