On 8 March 2011 11:07, EricB <[email protected]> wrote:

> Hello.
>
> I'm  trying to convert code to Guice and I'm looking for the Guice
> equivalent for the following spring behavior:
> @Autowired List<ConnectionStrategy> beans;
> Spring DI will provide a list of all classes that implements
> ConnectionStrategy assuming they are all annotated with @Component
> Now I'm trying to do the same with Guice.
>
> Multibinder might help but it still lacks some automation I need.
> Here is what I've got:
> Multibinder<ConnectionStrategy> strategiesBinder =
> Multibinder.newSetBinder(binder(), ConnectionStrategy.class);
>
> //Now this is the not fun part I don't wat to add this binding myself
> for each implementation.
> strategiesBinder.addBinding().to(DirectConnectionStrategy.class);
>
> As I have many connection strategies, and since I want to let others
> extend my application and provide their own strategies I wish guice
> could just figure out the classes that are annotated somehow and that
> I wont have to call the addBinding() method for each implementation I
> have.
> Now. I know I can write a provider and add a binding to that provider
> but I don't want to start messing with building a list in that
> provider by using reflection and such.
> What do you suggest?
>

the Injector SPI has a findBindingsByType method, so you could add something
like this in your module:

    @Provides
    List<ConnectionStrategy> getConnectionStrategies( Injector injector )
    {
        List<ConnectionStrategy> connectionStrategies = new
ArrayList<ConnectionStrategy>();
        for ( Binding<ConnectionStrategy> binding :
injector. findBindingsByType( TypeLiteral.get( ConnectionStrategy.class ) )
        {
            connectionStrategies.add( binding.getProvider().get() );    //
may want to wrap in try...catch for robustness?
        }
        return connectionStrategies;
    }

( caveat: I just typed up that code ad-hoc, haven't checked it actually
compiles :)

I use a similar technique in sisu-inject, although it's more complex since
it handles dynamic graphs of injectors where each one can come and go at any
time

Thanks.
>

-- 
Cheers, Stuart

-- 
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-guice?hl=en.

Reply via email to