Guice: One “Provider” for multiple implementations

后端 未结 2 1394
夕颜
夕颜 2021-01-16 15:28

I have an interface that has 20 or so annotated implementations. I can inject the correct one if I know which I need at compile time, but I now need to dynamically inject on

2条回答
  •  醉酒成梦
    2021-01-16 15:56

    Inject a MapBinder.

    In your module, load the bindings into the MapBinder, then make your runtime parameters injectable as well. This example is based on the one in the documentation:

    public class SnacksModule extends AbstractModule {
      protected void configure() {
        MapBinder mapbinder
               = MapBinder.newMapBinder(binder(), String.class, Snack.class);
        mapbinder.addBinding("twix").to(Twix.class);
        mapbinder.addBinding("snickers").to(Snickers.class);
        mapbinder.addBinding("skittles").to(Skittles.class);
      }
    }
    

    Then, in your object, inject the Map and the parameter. For this example I will assume you've bound a java.util.Properties for your runtime parameters:

    @Inject
    public MyObject(Map> snackProviderMap, Properties properties) {
      String snackType = (String) properties.get("snackType");
      Provider = snackProviderMap.get(property);
      
      // etc.
    }
    

    Note, with the same MapBinder you can inject either a simple Map or a Map>; Guice binds both.

提交回复
热议问题