1
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.

ealeon
  • 12,074
  • 24
  • 92
  • 173

1 Answers1

3

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.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
  • so this is needed even if i want to return "new Hashset<>()"? datafilling the hashset happens else where. i just want it to instantiate a generic hashset. Provider is needed even for that? – ealeon Jun 24 '19 at 20:51
  • @ealeon Yeah, in your provider you'd just do return new HashSet or whatever. You can also do it on a global basis, if for example every hash set returns a new hash set, you can bind the hash set class to the provider that returns a new hash set, then you only need to bind that once. – Matthew Kerian Jun 25 '19 at 00:27
  • @ealeon I've updated the answer with how you can "datafill" the set in several places rather than in one single place. – Olivier Grégoire Jun 25 '19 at 08:01