I use HK2 to resolve service dependencies in the Jersey / Jetty web service. I have a situation where for one specific interface I want to use a specific implementation as the default implementation. By default, I mean the absence of names or classifiers - this is what you get if you do not specify any annotations on top of the field or argument. However, in a few very specific situations, I want to provide an alternative implementation that will qualify using annotation.
As a result of my experiments, I really got this to work reliably using the ranked() qualifier in my bindings. Apparently, the highest rank becomes default. However, I donโt understand why this works, and I am worried that I am writing code that depends on the undocumented details of the HK2 implementation, which may change when upgrading versions.
Here is a contrived example of interesting parts of what I am doing. Is ranked() what I should use to indicate the "default" and annotated service options? Should I use a different technique?
public interface IFoo { public String getString(); } public class DefaultImpl implements IFoo { public String getString() { return "Default Implementation"; } } public class AnnotatedImpl implements IFoo { public String getString() { return "Annotated Implementation"; } } public class Bindings extends AbstractBinder { @Override public void configure() { ServiceBindingBuilder<DefaultImpl> defaultImpl = bind(DefaultImpl.class) .to(IFoo.class); defaultImpl.ranked(9); ServiceBindingBuilder<AnnotatedImpl> annotatedImpl = bind(AnnotatedImpl.class) .qualifiedBy(new MyAnnotationQualifier()) .to(IFoo.class); annotatedImpl.ranked(1); } } public class MyService { @Inject public MyService( IFoo defaultImplementation, @MyAnnotation IFoo annotatedImplementation) {
source share