views:

73

answers:

1

I have a guice based app that now needs multiple instances of a given type so I plan on using a named annotation to disambiguate the dependencies. However a dependency of this type also needs to vary based on which one I get.

To illustrate lets say I have

@Singleton
public class FooCache {
    private final FooCacheListener listener;
    @Inject 
    public FooCache(FooCacheListener listener) {
        this.listener = listener;
    }
    // do stuff
}

and then lets say I have a need for 2 separate instances so I might have

@ThatOne FooCache

in one class and

@ThisOne FooCache

in another.

Now lets say I want a different listener in each case (maybe one writes something to a database and the other sends a notification over JMS or to some distributed cache). How would I do that? I can't see that I can stick a name on the FooCacheListener as I'd need a different name in one situation vs the other whereas I have just one place here. The only way I can think of doing this is by subclassing FooCache but that seems a really clumsy approach to me.

Cheers Matt

+2  A: 

You might be able to use PrivateModules. Go here and scroll down to How do I build two similar but slightly different trees of objects? It is a way to have two different instances of the same class,which sounds almost exactly what you are trying to do. You could pass in your cachelisteners instead of the "lefty" and "righty" passed in in the example. There are more links with details from there if it looks like what you want.

Another option might be to inject a factory, which is also discussed in the link above, in the question How do I pass a parameter when creating an object via Guice?

Peter Recore
somehow I missed that in the docs, that is what I'm looking for. Thanks.
Matt