java - Guice Binding for List of generic Objects -
what binding statement need tell guice want onefoo , twofoo injected bar list of foo? setup here chain of responsibility. right have 2 implementations, bar doesn't need know that.
@inject bar(list<foo> foos) {...} ... class onefoo implements foo { @inject onefoo(...) {...} ... class twofoo implements foo { @inject twofoo(...) {...} but i'm struggling using types, typeliteral, etc configure binding 2 foo implementations given bar.
if know @ compile time bindings, can use @provides method in module:
class mymodule extends abstractmodule() { @override protected void configure() { // ... } @provides @inject public list<foo> foos(onefoo one, twofoo two) { return arrays.aslist(one, two); } } you can expand foos's argument list needed. similar, more verbose approach, use provider:
protected void configure() { bind(new typeliteral<list<foo>>() {}) .toprovider(foolistprovider.class); } static class foolistprovider implements provider<list<foo>> { @inject provider<onefoo> one; @inject provider<twofoo> two; public list<foo> get() { return arrays.aslist(one.get(), two.get()); } } in case want singleton list in onefoo , twofoo injected, can add @singleton annotation. recommend making list immutable @ point:
@singleton @provides @inject public list<foo> foos(onefoo one, twofoo two) { return collections.unmodifiablelist(arrays.aslist(one, two)); } if on other hand, want singleton list onefoo , twofoo not injected, can use typeliteral:
@override protected void configure() { bind(new typeliteral<list<foo>>() {}) .toinstance(arrays.aslist(new onefoo(), new twofoo())); } in case too, again, i'd suggest making list unmodifiable.
Comments
Post a Comment