Search code examples
javaguice

Google Guice: right way to inject primitive data structure


private HashSet<WorkWindow> childWorkWindows;

@Inject
public CompositeWorkWindows (
        HashSet childWorkWindows
) {
    this.childWorkWindows = childWorkWindows;
}

Would Guice know how to inject this automatically without having to specify anything in the module?

My concern is that i am specifying the type for HashSet in the private field.


Solution

  • You must first bind it

    In your configuration:

    @Provides HashSet<WorkWindow> provideChildWorkWindows() {
      // Create and return your HashSet<WorkWindow>
    }
    

    Then only it will be injectable in your CompositeWorkWindows.

    If you want to bind several, independant WorkWindow, use Guice's multibinding. But in that case, you should use the interface Set as recipient, instead of the HashSet implementation, because Guice will provide a Set but not a HashSet. Note that multibinding allows you to have the definitions of the elements in different modules.

    In MyModule.java:

    Multibinder<WorkWindow> workWindowBinder = Multibinder.newSetBinder(binder(), WorkWindow.class);
    workWindowBinder.addBinding().toInstance(new MyWorkWindow());
    

    In OtherModule.java:

    Multibinder<WorkWindow> workWindowBinder = Multibinder.newSetBinder(binder(), WorkWindow.class);
    workWindowBinder.addBinding().to(OtherWorkWindow.class);
    

    In FinalModule.java:

    Multibinder<WorkWindow> workWindowBinder = Multibinder.newSetBinder(binder(), WorkWindow.class);
    workWindowBinder.addBinding().toProvider(new FinalWorkWindowProvider());
    

    If all modules are present in an injector, you will get a Set that has a size of 3, containing the three different WorkWindow you created.