添加到子注入器中的 Multibinder

Jor*_*orn 5 java guice

我正在尝试将子注入器的 Guice 功能与 Multibinders 结合起来。例如:

public class Test {
    public static void main(String[] args) {
        Guice.createInjector(new FirstModule(), new SecondModule()); // works perfectly, returns set with 2 elements
        Guice.createInjector(new FirstModule()).createChildInjector(new SecondModule()); // fails: A binding to java.util.Set<Test$MyInterface> was already configured at Test$FirstModule.configure(Test.java:15).
    }

    private static class FirstModule extends AbstractModule {
        @Override
        protected void configure() {
            Multibinder.newSetBinder(binder(), MyInterface.class).addBinding().to(FirstImplementation.class);
        }
    }

    private static class SecondModule extends AbstractModule {
        @Override
        protected void configure() {
            Multibinder.newSetBinder(binder(), MyInterface.class).addBinding().to(SecondImplementation.class);
        }
    }

    private static interface MyInterface {}
    private static class FirstImplementation implements MyInterface {}
    private static class SecondImplementation implements MyInterface {}
}
Run Code Online (Sandbox Code Playgroud)

是否有可能以某种方式将子注入器添加到多重绑定中?

Jor*_*orn 4

据我所知,这是不可能的。如果在第一个注入器中请求该组对象,则必须使用来自第一个注入器的绑定来注入它。如果您随后创建一个子注入器并绑定一个附加值,那么您实际上会覆盖父注入器的 set 绑定,而 Guice 不允许这样做。