0

In the Guice FAQ, they talk about differentiating multiple instances with annotations (kind of).

My question: Can I bind a Impl to an Interface without an annotation, and bind another Impl to that same Interface with an annotation? Basically my first impl is going to act as a container for the others.

bind(SecurityAuthorizer.class).to(CompositeSecurityAuthorizer.class);
bind(SecurityAuthorizer.class)
    .annotatedWith(Names.named(ComponentAuthorizer.class.getSimpleName()))
    .to(ComponentAuthorizer.class).in(Singleton.class);

Bonus question, is our usage of Names.named(..) considered bad form? Just trying to avoid creating a ton of annotation classes, yet wanted the benefits of being able to refactor.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Snekse
  • 15,474
  • 10
  • 62
  • 77

1 Answers1

1

Yup, that should just work. You might want to also look at Multibindings, which is designed for scenarios like this one. The composite implementation would inject the set of interfaces:

public class CompositeSecurityAuthorizer {
    @Inject 
    CompositeSecurityAuthorizer(Set<SecurityAuthorizer> authorizers) {
        ...
    }
}
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • Unfortunately this is for a Gin module, so Multibindings aren't supported yet. http://code.google.com/p/google-gin/issues/detail?id=111 – Snekse Mar 18 '11 at 17:11