Generalize guice's robot-legs example with Multibinding

前端 未结 1 1601
难免孤独
难免孤独 2020-12-18 00:41

I have this use case that is very similar to the robot-legs example of Guice, except I don\'t know how many \"legs\" I have. Therefore I can\'t use the annotations needed fo

相关标签:
1条回答
  • 2020-12-18 01:26

    It looks like you're going to need to jump through some hoops to promite bindings from the private module so that they can be in the top-level injector's multibinding.

    This should work:

    public class SquareModule extends AbstractModule { // does not extend PrivateModule
      @Overide public void configure() {
        // this key is unique; each module needs its own!
        final Key<MyInterface> keyToExpose
            = Key.get(MyInterface.class, Names.named("square"));
    
        install(new PrivateModule() {
          @Override public void configure() {
    
            // Your private bindings go here, including the binding for MyInterface.
            // You can install other modules here as well!
            ...
    
            // expose the MyInterface binding with the unique key
            bind(keyToExpose).to(MyInterface.class);
            expose(keyToExpose);
          }
        });
    
        // add the exposed unique key to the multibinding
        Multibinder.newSetBinder(binder(), MyInterface.class).addBinding().to(keyToExpose);
      }
    }
    

    This workaround is necessary because multibindings need to happen at the top-level injector. But private module bindings aren't visible to that injector, so you need to expose them.

    0 讨论(0)
提交回复
热议问题