Injecting a generic factory in Guice

后端 未结 2 982
梦如初夏
梦如初夏 2020-12-16 15:55

The following code is an example of a factory that produces a Bar given a Foo. The factory doesn\'t care what T is:

相关标签:
2条回答
  • 2020-12-16 16:42

    One option is to just write the BarFactory boilerplate by hand:

    class BarImplFactory implements BarFactory {
      public <T> Bar<T> create(Foo<T> f) {
        return new BarImpl(f);
      }
    }
    

    The binding becomes

    bind(BarFactory.class).to(BarImplFactory.class);
    
    0 讨论(0)
  • 2020-12-16 16:42

    If you think of guice as a system of wiring similar to spring, then it doesn't really make sense to wire a generic instance. You're wiring specific instances to keys, so that when another instantiated class marks something with @Inject BarFactory you get the specific created instance.

    Since your implementation is generic, you haven't provided enough information to inject a specific instance. Although I haven't used factoryprovider, my assumption is that you'll need to bind the Barfactory to a fully parameterized instance, e.g. BarImpl<Concrete> instead of BarImpl )

    Incidentally since you're binding BarFactory.class if you want to bind multiple instances you're going to have to inflect them somehow, either by name, something like (haven't checked the syntax, but)

    bind(BarFactory.class).annotatedWith(Names.named("name1"))
          .toProvider( 
    
    or by generics, bind(BarFactory<Concrete>).toProvider...
    
    0 讨论(0)
提交回复
热议问题