Adding the same class multiple times into multibinder with different binding parameters.

885 views
Skip to first unread message

Jia Pu

unread,
Nov 20, 2013, 3:29:30 PM11/20/13
to google...@googlegroups.com
Let's same I have an abstract class with several subclasses:

public abstract AbstractFoo { }

public FooA extends AbstractFoo {}
public FooB extends AbstractFoo {}
public FooC extends AbstractFoo {}

There's also a class with following injection:

class Bar {
@Inject
public Bar(Foo foo) { }
}

Is it possible to add Bar multiple times into multibinder with different concrete Foo classes?

Multibinder<Bar> binder = Multibinder.newSetBinder(binder(), new Bar.class);
binder.addBinding .... // Now what?

Or did I completely miss the point of Guice here? I'm new to java world, BTW.

Armin Bahramshahry

unread,
Nov 20, 2013, 7:04:20 PM11/20/13
to google...@googlegroups.com
Take a look at @Named, https://code.google.com/p/google-guice/wiki/BindingAnnotations, I believe that's what you wanna do

Jia Pu

unread,
Nov 21, 2013, 4:25:30 PM11/21/13
to google...@googlegroups.com
I did try to achieve my goal using annotation. It works. But I wonder if there's more concise way. My current solution is:

class BarA extends Bar {
@Inject
public Bar(@Named("A") Foo foo) { }
}

class BarB extends Bar {
@Inject
public Bar(@Named("B") Foo foo) { }
}

Then in the module:

bind(AbstractFoo.class).annotatedWith(Names.named("A")).to(FooA.class);
bind(AbstractFoo.class).annotatedWith(Names.named("B")).to(FooB.class);

Multibinder<Bar> binder = Multibinder.newSetBinder(binder(), new Bar.class);
binder.addBinding().to(BarA.class);
binder.addBinding().to(BarB.class);

The problem here is that I need to create two dummy subclass, BarA and BarB, in order to utilize annotation. I wonder if there's a way to reduce this sort of boilerplate code.

Stephan Classen

unread,
Nov 22, 2013, 2:43:38 AM11/22/13
to google...@googlegroups.com
you can achieve the same result with private modules. Then you don't have to create the dummy classes.
see: https://groups.google.com/forum/#!topic/google-guice/h70a9pwD6_g
--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice...@googlegroups.com.
To post to this group, send email to google...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-guice.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages