我有一组模块,并且对如何在创建模块时访问另一个模块的绑定感兴趣。
我知道可以在第二个模块中执行requireBinding
并从那里访问String。但这不是我从外部依赖项获得的接口,因此无法更改。
我看到的唯一选择是将其一致地传递给所有模块以具有平等的访问权限。
请参见以下示例:
package com.amazon.nlgeysercontrolplane.guice;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import org.junit.Test;
import static com.google.inject.Guice.createInjector;
public class MultiModuleTest {
static class ChildModule2 extends AbstractModule {
String f;
public ChildModule2(final String f) { this.f = f; }
protected void configure() { }
}
static class ChildModule extends AbstractModule {
@Override
protected void configure() {
bind(String.class).toInstance("foobar");
}
}
@Test
public void testGuiceModules() {
Injector inj = createInjector(new AbstractModule(){
@Override
protected void configure() {
install(new ChildModule());
String f = binder().getProvider(String.class).get();
install(new ChildModule2(f));
}
});
}
}
这是我收到的异常(与文档一致)。
Caused by: java.lang.IllegalStateException: This Provider cannot be used until the Injector has been created.
at com.google.common.base.Preconditions.checkState(Preconditions.java:173)
at com.google.inject.spi.ProviderLookup$1.get(ProviderLookup.java:102)
at com.google.inject.AbstractModule.configure(AbstractModule.java:62)
at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:340)
at com.google.inject.spi.Elements.getElements(Elements.java:110)
at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:138)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:104)
0.016