Kelvin Chung
Kelvin Chung

Reputation: 1377

Guice: Injecting a Module and then installing it

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?

Upvotes: 0

Views: 522

Answers (1)

Tavian Barnes
Tavian Barnes

Reputation: 12922

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
    }
}

Upvotes: 3

Related Questions